Are even square jagged arrays faster?

J

James dean

I done a test and i really do not know the reason why a jagged array who
has the same number of elements as a multidimensional array is faster
here is my test. I assign a value and do a small calculation. Even if i
initialise the jagged array inside the function it is still much faster.
Are these results correct?. If i put the initialisation loop in the
constructor its ridiculously faster but even here its 4 times
faster...is this correct?

private int[,] multi= new int[2000, 2000];
private int[][] jagged = new int[2000][];

private void btnArrayPerformance_Click(object sender, System.EventArgs
e)
{
for(int x = 0;x < 2000;x++)
{
jagged[x] = new int[2000];
}
for(i = 0;i < 2000;i++)
for(j = 0;j < 2000;j++)
{
jagged[j][k] = 8;
jagged[j][k] = (8 * 2);
}
}

private void btnMulti_Click(object sender, System.EventArgs e)
{
for(i = 0;i < 2000;i++)
for(j = 0;j < 2000;j++)
{
multi[j,k] = 8;
multi[j,k] = (8 * 2);
}
}
 
G

Guest

Hi,

Yes, is totally true,and even faster if you access first to your first
dimension and then the second if a nested for.

The reason for jagged arrays superior performance is that the CLR is
optimized to access elements of vectors and, even if the accessing a jagged
array's element requires two vector access, the combined operatin is still
faster than a two-dimensional array. Also, jagged arrays consumes less memory
and their elements can be referenced faster.

From the Assembler point of view remember to check your access
[x,y,z]

for (x)
for (y)
for (z)

You will be surprise that the order can double the speed.

cheers
Salva
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top