Why is “while (i++ < n) {}” significantly slower than “while (++i < n) {}”

后端 未结 5 2143
长发绾君心
长发绾君心 2020-12-04 14:16

Apparently on my Windows 8 laptop with HotSpot JDK 1.7.0_45 (with all compiler/VM options set to default), the below loop

final int n = Integer.MAX_VALUE;
in         


        
5条回答
  •  不思量自难忘°
    2020-12-04 14:44

    The difference between ++i and i++ is that ++i effectively increments the variable and 'returns' that new value. i++ on the other hand effectively creates a temp variable to hold the current value in i, then increments the variable 'returning' the temp variable's value. This is where the extra overhead is coming from.

    // i++ evaluates to something like this
    // Imagine though that somehow i was passed by reference
    int temp = i;
    i = i + 1;
    return temp;
    
    // ++i evaluates to
    i = i + 1;
    return i;
    

    In your case it appears that the increment won't be optimized by the JVM because you are using the result in an expression. The JVM can on the other hand optimize a loop like this.

    for( int i = 0; i < Integer.MAX_VALUE; i++ ) {}
    

    This is because the result of i++ is never used. In a loop like this you should be able to use both ++i and i++ with the same performance as if you used ++i.

提交回复
热议问题