Array of Objects or Object with arrays?
I have a design choice to make: Do I create an array of wrapper objects each conta开发者_开发知识库ining a few distinct values, or do I create an object that contains a few distinct 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 would be more efficient only because there would be fewer objects and thus less overhead, but would the double[]'s be just as expensive?
Do you know that there will be a significant issue here? How many of these are you going to create?
You shouldn't worry too much about the performance to start with - ask yourself whether a single node logically has multiple pairs of values or just a single pair. Let your classes follow what you're modelling - keep an eye on performance and memory usage, but don't let it dictate your design to the exclusion of a natural model.
Memory model ->
Array = value1, value2, value3 ...
Object = Field1, Field2, Field3...
If you have array of objects the memory looks like: Field1, Field2, Field3, Field1, Field2, Field3...
If you have an object with arrays the memory looks like Field1, Field1, Field1.... Field2, Field2, Field2...
Access to contiguous memory is faster than access to non-contiguous memory.
If you have an array of 10*20, it means 10*20*2 in the first case and 10*(20+20) in the second case. In both cases, that makes 400. So there is no difference in terms of memory.
If your array is only containing a couple of nodes, you may as well consider a HashMap where K is an immutable class containing the array coordinates of a given node and V an object containing val1 and val2 for that node. You would only allocate memory per node, not for the whole array.
精彩评论