資料空間區域性性帶來的效率差異測試
通過二維陣列的訪問方式來測試資料的空間區域性性帶來的效率差異性,程式碼如下:
static void test1(){
int[][] data = new int[10000][10000];
int temp=1;
long start = System.currentTimeMillis();
for(int i=0;i<10000;i++){
for(int j=0;j<10000;j++){
temp=data[i][j];
}
}
long end = System.currentTimeMillis();
System.out.println(end-start);
}
static void test2(){
int[][] data = new int[10000][10000];
int temp=1;
long start = System.currentTimeMillis();
for(int i=0;i<10000;i++){
for(int j=0;j<10000;j++){
temp=data[j][i];
}
}
long end = System.currentTimeMillis();
System.out.println(end-start);
}
第一種方式比第二種方法的效率要高30倍左右,本人測試機器是i5-4210H處理器,具有良好空間區域性性的程式會非常高效。一般而言陣列比連結串列具有良好的空間區域性性,比如字首樹通過雙陣列trie實現會比普通的trie樹高效很多。