For example, would a full int[50][8] use more resources (RAM and CPU) than 8 full int[50] arrays?
-
Do you have some code sample we can test?OscarRyz– OscarRyz2009-02-23 18:56:26 +00:00Commented Feb 23, 2009 at 18:56
-
What are you trying to achieve? If you have performance problems it is probably not due to the way you organize your arrays.starblue– starblue2009-02-23 19:10:05 +00:00Commented Feb 23, 2009 at 19:10
6 Answers
In the first case you have one array object pointing to fifty array objects holding 8 int's. So 1 + 50 array objects + fifty pointers in the first array object.
In the second case you have one array object pointing to 8 array objects holding 50 int's. So 1 + 8 array objects + eight pointers in the first array object. Holding the int's is a wash.
There is not a good way to evaluate CPU usage for this.
2 Comments
There appears to be three things to compare here.
new int[50][8]new int[8][50]new int[400]
Now, I get this confused, but the way to remember is to think of new int[50][] which is valid.
So new int[50][8] is an array of 50 arrays of size 8 (51 objects). new int[8][50] is an array of 8 arrays of size 50 (9 objects). 9 objects will have a lower overhead than 51. new int[400] is just one object.
However, it at this size it probably doesn't make any measurable difference to the performance of your program. You might want to encapsulate the array(s) within an object that will allow you to change the implementation and provide a more natural interface to client code.
2 Comments
One additional useage point (came from a reference I unfortunately can't find now, but fairly commonsensical)-
The authors of this paper were testing various ways of compressing sparse arrays into mutidimensional arrays. One thing they noticed is that it makes a difference in terms of speed which way you iterate -
The idea was that if you have int[i][j] it was faster to do
for (i) {
for (j)
than to do
for (j) {
for (i)
because in the first instance you're iterating through elements stored contiguously.
1 Comment
you could tweak a tiny amout of memory by using an int[] myInt = int[400] array, and manually accessing an int at position (x,y) with myInt[x+y*50] that would save you 50 32-bit pieces of memory. accessing it that way will maybe (who knows exactly what the hotspot compiler does to this..) take one more instruction for the multiplication.
that kind of micro-optimisation will most likely not make your app perform better, and it will decrease readability.