【Java基础之多维数组访问】访问多维数组时潜在的性能问题

来源:互联网 发布:java在线学习系统源码 编辑:程序博客网 时间:2024/06/08 02:05

[c-sharp] view plaincopyprint?
  1. boolean[][] b = new boolean[8000][1000];  
  2.   
  3. long s = System.currentTimeMillis();  
  4.   
  5. for ( int i = 0; i <1000 ; i++ ) {  
  6.     for ( int j = 0; j < 8000; j++ ) {  
  7.         b[j][i] = true;  
  8.     }  
  9. }  
  10.   
  11. System.out.print(System.currentTimeMillis() - s);  

 

执行结果:453

 

[java] view plaincopyprint?
  1. boolean[][] b = new boolean[8000][1000];  
  2.   
  3. long s = System.currentTimeMillis();  
  4.   
  5. for ( int i = 0; i <8000 ; i++ ) {  
  6.     for ( int j = 0; j < 1000; j++ ) {  
  7.         b[i][j] = true;  
  8.     }  
  9. }  
  10.   
  11. System.out.print(System.currentTimeMillis() - s);  

 

执行结果:16

 

所以,在访问二维数组时,应该顺着子数组进行遍历,这样的访问效率是最高的。而在不同的子数组中来回遍历,就需要不断的重新计算指针偏移量,会导致效率非常低。

0 0
原创粉丝点击