Enhanced for loop performance worse than traditional indexed lookup?

后端 未结 4 1446
小蘑菇
小蘑菇 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条回答
  •  感情败类
    2020-12-16 02:20

    GravityBringer's number doesn't seem right, because I know ArrayList.get() is as fast as raw array access after VM optimization.

    I ran GravityBringer's test twice on my machine, -server mode

    50574847
    43872295
    30494292
    30787885
    (2nd round)
    33865894
    32939945
    33362063
    33165376
    

    The bottleneck in such tests is actually memory read/write. Judging from the numbers, the entire 2 arrays are in my L2 cache. If we decrease the size to fit L1 cache, or if we increase the size beyond L2 cache, we'll see 10X throughput difference.

    The iterator of ArrayList uses a single int counter. Even if VM doesn't put it in a register (the loop body is too complex), at least it will be in the L1 cache, therefore r/w of are basically free.

    The ultimate answer of course is to test your particular program in your particular environment.

    Though it's not helpful to play agnostic whenever a benchmark question is raised.

提交回复
热议问题