简体   繁体   中英

Initializing new array as function argument, in a loop, in Java. Performance

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);

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM