time complexity or hidden cost of .length in java

后端 未结 5 1362
失恋的感觉
失恋的感觉 2020-12-06 11:03

I was looking at a project in java and found a for loop which was written like below:

for(int i=1; i

        
5条回答
  •  心在旅途
    2020-12-06 11:08

    For your convenience, I've microbenchmarked it. The code:

    public class ArrayLength
    {
      static final boolean[] ary = new boolean[10_000_000];
      static final Random rnd = new Random();
      @GenerateMicroBenchmark public void everyTime() {
        int sum = rnd.nextInt();
        for (int i = 0; i < ary.length; i++) sum += sum;
      }
      @GenerateMicroBenchmark public void justOnce() {
        int sum = rnd.nextInt();
        final int length = ary.length;
        for (int i = 0; i < length; i++) sum += sum;
      }
    }
    

    The results:

    Benchmark                     Mode Thr    Cnt  Sec         Mean   Mean error    Units
    o.s.ArrayLength.everyTime    thrpt   1      3    5    40215.790     1490.800 ops/msec
    o.s.ArrayLength.justOnce     thrpt   1      3    5    40231.192      966.007 ops/msec
    

    Summary: no detectable change.

提交回复
热议问题