循环

 1 static class Foo {
 2     int mSplat;
 3 }
 4 
 5 Foo[] mArray = ...
 6 
 7 public void zero() {
 8     int sum = 0;
 9     for (int i = 0; i < mArray.length; ++i) {
10         sum += mArray[i].mSplat;
11     }
12 }
13 
14 public void one() {
15     int sum = 0;
16     Foo[] localArray = mArray;
17     int len = localArray.length;
18 
19     for (int i = 0; i < len; ++i) {
20         sum += localArray[i].mSplat;
21     }
22 }
23 
24 public void two() {
25     int sum = 0;
26     for (Foo a : mArray) {
27         sum += a.mSplat;
28     }
29 }

zero() is slowest, because the JIT can't yet optimize away the cost of getting the array length once for every iteration through the loop.

one() is faster. It pulls everything out into local variables, avoiding the lookups. Only the array length offers a performance benefit.

two() is fastest for devices without a JIT, and indistinguishable from one() for devices with a JIT. It uses the enhanced for loop syntax introduced in version 1.5 of the Java programming language.

posted @ 2017-07-07 12:53  戴杭林  阅读(141)  评论(0编辑  收藏  举报