-3

Is it more efficient to be doing this:

double[] a = new double[5];
for (int i = 0; i < a.length; i++) {
    a[i] = i;
}

rather than this:

public class DataStore {
    public double a, b, c, d, e;

    public DataStore(double a, double b, double c, double d, double e) {
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
        this.e = e;
    }
}
...
new DataStore(0, 1, 2, 3, 4);

Is there any added efficiency that would greatly impact the performance of the java application using the "double[]" array? Or would the difference only be negligible?

  • 7
    Repeat after me: premature optimization is the root of all evil. Do what makes sense. – John Dvorak Jul 12 '16 at 03:49
  • you can also try `Arrays.asList(1,2,3,4,5)` – bananas Jul 12 '16 at 03:50
  • 2
    Scalability? We don't need no stinkin' scalability! – John3136 Jul 12 '16 at 03:50
  • 1
    How about `new DataStore(4, 3, 2, 1, 0);` so you can use the natural gravitational force of decreasing numbers – Scary Wombat Jul 12 '16 at 03:53
  • Do the 5 values represent the *same*, so you'd want to loop through and handle them the same? If so, option 1 is right, and option 2 is wrong, since you cannot loop through them (without using slow reflection). Are the 5 values *different*, so naming them individually makes the code more readable/understandable? Then option 1 is wrong and option 2 is right. As you can see, the choice is not about performance, it's about your *code*. – Andreas Jul 12 '16 at 04:21

1 Answers1

3

Yes, primitive scalar types like double[] will be faster for most uses. Much faster, in many cases. However, it is highly unlikely that you'll notice any kind of difference in most applications.

Someone else did a relevant benchmark here.

But, always remember:

Premature optimization is the root of all evil in programming!

Community
  • 1
  • 1
Will
  • 24,082
  • 14
  • 97
  • 108