modern for loop for primitive array

前端 未结 5 2003
慢半拍i
慢半拍i 2021-02-05 16:39

Is there any performance difference between the for loops on a primitive array?

Assume:

double[] doubleArray = new double[300000];


for (double var: do         


        
5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-05 17:31

    Your hand-written, "old" form executes fewer instructions, and may be faster, although you'd have to profile it under a given JIT compiler to know for sure. The "new" form is definitely not faster.

    If you look at the disassembled code (compiled by Sun's JDK 1.5), you'll see that the "new" form is equivalent to the following code:

    1: double[] tmp = doubleArray;
    2: for (int i = 0, y = tmp.length; i < y; i++) {
    3:   double var = tmp[i];
    4:   someComplexCalculation(var);
    5: }
    

    So, you can see that more local variables are used. The assignment of doubleArray to tmp at line 1 is "extra", but it doesn't occur in the loop, and probably can't be measured. The assignment to var at line 3 is also extra. If there is a difference in performance, this would be responsible.

    Line 1 might seem unnecessary, but it's boilerplate to cache the result if the array is computed by a method before entering the loop.

    That said, I would use the new form, unless you need to do something with the index variable. Any performance difference is likely to be optimized away by the JIT compiler at runtime, and the new form is more clear. If you continue to do it "by hand", you may miss out on future optimizations. Generally, a good compiler can optimize "stupid" code well, but stumbles on "smart" code.

提交回复
热议问题