I’m making a program for myself and this question popped up. This program deals with graphics so I have to keep performance in mind.
Is there a difference in performance if I use several variables or if I use an array with hard coded indexes? If there is, which is better?
To illustrate:
R = (X * 3.2406) + (Y * -1.5372) + (Z * -0.4986);
G = (X * -0.9689) + (Y * 1.8758) + (Z * 0.0415);
B = (X * 0.0557) + (Y * -0.2040) + (Z * 1.0570);
or
RGB[0] = (XYZ[0] * 3.2406) + (XYZ[1] * -1.5372) + (XYZ[2] * -0.4986);
RGB[1] = (XYZ[0] * -0.9689) + (XYZ[1] * 1.8758) + (XYZ[2] * 0.0415);
RGB[2] = (XYZ[0] * 0.0557) + (XYZ[1] * -0.2040) + (XYZ[2] * 1.0570);
Thanks in advance.
You are most likely faster with separate variables.
Why? The JVM optimizes your code at runtime to make it faster. It tracks the flow and values of each variable to learn how to optimize code. For example it might realize that a parameter to a method is never assigned and thus constant. But it does not do so for each element of an array. An array is just considered as one huge mutable variable. So you are more likely to get optimal code when using separate variables.