An array of objects or objects with arrays?

I have a design choice: am I creating an array of shell objects, each of which contains several different values, or am I creating an object containing several different arrays of values?

Option 1:

Node[][] nodes; class Node{ double val1; double val2; } 

Option 2:

 Node[] nodes; class Node{ double[] val1; double[] val2; } 

My gut says that option 2 will be more effective just because there will be fewer facilities and therefore less overhead, but will the double [] be just as expensive?

+4
source share
3 answers

Memory model β†’

Array = value1, value2, value3 ...

Object = Field1, Field2, Field3 ...

If you have an array of objects, then the memory looks like this: Field1, Field2, Field3, Field1, Field2, Field3...

If you have an object with arrays, then the memory looks like Field1, Field1, Field1.... Field2, Field2, Field2...

Continuous memory access is faster than non-contiguous memory access.

+1
source

Do you know that there will be a significant problem? How many of them are you going to create?

You don't have to worry too much about performance to start with it - ask yourself if one node has logically multiple pairs of values ​​or only one pair. Let your classes follow what you model, keep an eye on performance and memory usage, but don't let it dictate your design, excluding the natural model.

+7
source

If you have an array of 10 * 20, that means 10 * 20 * 2 in the first case and 10 * (20 + 20) in the second case. In both cases, this is 400. Thus, there is no difference in memory.

If your array contains only a couple of nodes, you can also consider HashMap, where K is an immutable class containing the coordinates of the array of a given node and V is an object containing val1 and val2 for this node, you would allocate memory on the node, not the entire array .

+1
source

All Articles