Enhanced for loop performance worse than traditional indexed lookup?

后端 未结 4 1453
小蘑菇
小蘑菇 2020-12-16 01:38

I just came across this seemingly innocuous comment, benchmarking ArrayList vs a raw String array. It\'s from a couple years ago, but the OP writes

I

4条回答
  •  旧时难觅i
    2020-12-16 02:09

    The situation has gotten worse for ArrayLists. On my computer running Java 6.26, there is a fourfold difference. Interestingly (and perhaps quite logically), there is no difference for raw arrays. I ran the following test:

        int testSize = 5000000;
    
        ArrayList list = new ArrayList();
        Double[] arr = new Double[testSize];
    
        //set up the data - make sure data doesn't have patterns
        //or anything compiler could somehow optimize
        for (int i=0;i

    The arithmetic in the loops is to prevent the JIT compiler from possibly optimizing away some of the code. The effect of the arithmetic on performance is small, as the runtime is dominated by the ArrayList accesses.

    The runtimes are (in nanoseconds):

    ArrayList foreach: 248,351,782

    ArrayList get(): 60,657,907

    array foreach: 27,381,576

    array direct indexing: 27,468,091

提交回复
热议问题