c# - I thought 2d Arrays get converted to 1d arrays by the compiler, why is it faster even when taking cache misses into consideration? -


i read top posts here #performance , #optimization , there lot of posts 2d array performance, c , c++ , said best practice switch x , y iteration limit cache-misses.

i tried same out in c# , tried 1d approach 2d array , considerably faster. why 1d version lot faster (optimal?) 2d one? generating fewer cache misses?

setup:

int[,] testarr = new int[testsize, testsize]; int[] testarr1dim = new int[testsize * testsize]; random r = new random(); (int x = 0; x < testsize; x++) {     (int y = 0; y < testsize; y++)     {         int tmp = r.next();         testarr[x, y] = tmp;         testarr1dim[(y + x * testsize)] = tmp;     }  } 

slow 2d array iteration:

 (int y = 0; y < testsize; y++)  {                 (int x = 0; x < testsize; x++)                 {                     counter += testarr[x, y]+2;                 }   } 

fast 2d array iteration: bit more twice speed of slow 2d array

 (int x = 0; x < testsize; x++)  {                 (int y = 0; y < testsize; y++)                 {                     counter += testarr[x, y]+2;                 }   } 

1d array iteration: bit more twice speed of fast 2d array

for (int x = 0; x < testsize; x++) {                 (int y = 0; y < testsize; y++)                 {                     counter += testarr1dim[(y + x * testsize)]+2;                 } } 

hanspassant suggester jagged array: ~10% slower 1d array

for (int x = 0; x < testsize; x++) {                 (int y = 0; y < testsize; y++)                 {                     counter += jaggedarr[x][y]+2;                 } } 

hanspassant suggested hoisting jagged array: faster 1d approach

for (int x = 0; x < testsize; x++) {                 var col = jaggedarr[x];                 (int y = 0; y < testsize; y++)                 {                     counter +=col[y]+2;                 } } 


Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -