开发者

For-loop Length Local Variable Micro Optimization?

开发者 https://www.devze.com 2023-02-23 08:47 出处:网络
In a lot of programming languages and their micro-opt开发者_如何学Goimizations, I\'ve seen that declaring the length of an array within a for-loop has performance implications especially in PHP and Ja

In a lot of programming languages and their micro-opt开发者_如何学Goimizations, I've seen that declaring the length of an array within a for-loop has performance implications especially in PHP and JavaScript:

for i = 0, length = arr.length; i < length; ++i

I've seen this format used in C++ and some Java source codes as well. Is this micro-optimization true for all programming languages? If this is a language-agnostic micro optimization, shouldn't it already be optimized from within compilers?


Well, I thought that the Java compiler will take care about this kind of optimization, but it isn't so:

public static void main(String[] args) {
    String[] array = new String[10000000];
    Arrays.fill(array, "Test");
    long startNoSize = Calendar.getInstance().getTimeInMillis();
    for(int i=0; i< array.length;i++)
    {
        array[i]=String.valueOf(i+1);
    }
    long finishNoSize = Calendar.getInstance().getTimeInMillis();
    System.out.println(finishNoSize-startNoSize);
    System.out.println("Size saved");
    int length = array.length;
    long startSize = Calendar.getInstance().getTimeInMillis();
    for(int i=0; i< length;i++)
    {
        array[i]=String.valueOf(i+2);
    }
    long finishSize = Calendar.getInstance().getTimeInMillis();
    System.out.println(finishSize-startSize);
}

After some consecutive runs the result is like this:

6207
Size saved
4594

So there is a difference of 1500 milliseconds.

UPDATE When the loops are reversed, the result is reversed too :) So there is no issue with lack of optimization.

So the in Java the calling of Container.size doesn't affect the performance.


The problem for the compiler is to know that arr.length will return the same every iteration in the loop. Sometimes it does not, for example, when the loop body inserts new elements into arr.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号