简体   繁体   English

在Java中循环地将新数组初始化为函数参数。 性能

[英]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? 是否为下面的代码为每个循环运行分配了新的float数组?

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. 请注意,尽管您所有的colorize调用都将共享float[]数组,所以更改一个内容将对其全部更改。 That's unlikely to be a problem in this case but something to be aware of. 在这种情况下,这不太可能成为问题,但需要注意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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