In C# there are 2 ways to create mutlidimensional arrays.
int[,] array1 = new int[32,32];
int[][] array2 = new int[32][];
for(int i=0;i<32;i++) array2[i]
In Java you are declaring an array of arrays.
You can see this by the following code:
int[][] arrOfArr = new int[5][];
arrOfArr[0] = new int[5];
arrOfArr[1] = new int[1];
arrOfArr[2] = new int[9];
...
int[][] arr = new int[3][3];
is just shorthand for:
int[][] arr = new int[3][];
arr[0] = new int[3];
arr[1] = new int[3];
arr[2] = new int[3];
It is an array of arrays with the same performance tradeoffs as in C#. If you know that your array of arrays is not going to be jagged, then you can wrap it in a class to get 2-d indexing on a 1-d backing array.
You are incorrect; jagged (nested) arrays are faster. (the CLR is optimized for them)
Java does not support true multi-dimensional arrays; that's a jagged array.
The Java syntax automatically creates all of the inner arrays; in C#, that would need a separate loop.
I was translating some Java code to C# - here is how I did the Jagged array
//Java
private static int grad3[][] = {{1,1,0},{-1,1,0},{1,-1,0},{-1,-1,0},{1,0,1},{-1,0,1},{1,0,-1},{-1,0,-1},{0,1,1},{0,-1,1},{0,1,-1},{0,-1,-1}};
//C#
private static int[,] grad3setup = { { 1, 1, 0 }, { -1, 1, 0 }, { 1, -1, 0 }, { -1, -1, 0 }, { 1, 0, 1 }, { -1, 0, 1 }, { 1, 0, -1 }, { -1, 0, -1 },
{ 0, 1, 1 }, { 0, -1, 1 }, { 0, 1, -1 }, { 0, -1, -1 } };
private static int[][] grad3
{
get
{
int[][] grad3 = new int[12][];
for (int i = 0; i < grad3.Length; i++)
{
grad3[i] = new int[3] { grad3setup[i, 0], grad3setup[i, 1], grad3setup[i, 2] };
}
return grad3;
}
}
It's still an array of arrays. It's just that in C# you'd have to create each subarray in a loop. So this Java:
// Java
int[][] array3 = new int[32][32];
is equivalent to this C#:
// C#
int[][] array3 = new int[32][];
for (int i = 0; i < array3.Length; i++)
{
array3[i] = new int[32];
}
(As Slaks says, jagged arrays are generally faster in .NET than rectangular arrays. They're less efficient in terms of memory though.)
Because people were concerned about the performance of multi-dimension vs staggered arrays in .NET, I implemented a few tests and benchmarked the results on 8k by 8k elements:
The tests were:
And the results:
one <> Elapsed Time: 0.543558s
two <> Elapsed Time: 0.8911516s
three <> Elapsed Time: 0.8908123s
four <> Elapsed Time: 1.1367238s
five <> Elapsed Time: 0.3039648s
six <> Elapsed Time: 0.8110969s
seven <> Elapsed Time: 0.2629394s
For fun I ran them on the WP7 emulator as well, and got similar numbers.
Code of the test function is here.