Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of Objects or Object with arrays?

I have a design choice to make: Do I create an array of wrapper objects each containing 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?

like image 818
Andrew Avatar asked Jan 19 '23 00:01

Andrew


1 Answers

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.

like image 147
Jon Skeet Avatar answered Jan 29 '23 12:01

Jon Skeet