1

Is a new float array allocated for every loop run for the code below?

for (Element e : elements) e.colorize( new float[] { 0.5f, 0.5f, 0.5f, 0.5f } );

Is there a performance gain in changing it into the following?

float[] color = new float[] { 0.5f, 0.5f, 0.5f, 0.5f };
for (Element e : elements) e.colorize(color);
1
  • it is a performance gain if the number of elements is greater than 1. if there are no elements you would create the array anyways. :) Commented Aug 13, 2015 at 21:24

2 Answers 2

3

There will be a performance gain primarily because there is no longer any memory allocation overhead, and you save tons of space. But the more important part is that you're colorizing the same array in the second code example, whereas in the first one you are colorizing a different array every time. If this is what you want, great! If not, then you need to rethink your code.

Sign up to request clarification or add additional context in comments.

1 Comment

I was just wondering if some, for example compile-time, optimization might come into play, because clearly new float[] { 0, 0, 0, 0 } is the same at every loop run. But my thinking was faulty, because there couldn't be any optimization of this sort, as compiler doesn't know what do I wish to do in colorize() function with the given array-argument. So it couldn't assume that I don't care about further modifying of color, and initialize only one array in both examples...
1

Yes, you are correct. The second one will be more efficient as the array will only be created and initialized once.

Just be aware though that all your colorize calls will be sharing the float[] array, so changing the contents of one will change it for all of them. That's unlikely to be a problem in this case but something to be aware of.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.