Array vs Slice: accessing speed

前端 未结 2 849
名媛妹妹
名媛妹妹 2020-12-14 03:08

This question is about the speed of accessing elements of arrays and slices, not about the efficiency of passing them to functions as arguments.

I would exp

相关标签:
2条回答
  • 2020-12-14 03:27

    Comparing the amd64 assembly of both BenchmarkArrayLocal and BenchmarkSliceLocal (too long to fit in this post):

    The array version loads the address of a from memory multiple times, practically on every array-access operation:

    LEAQ    "".a+1000(SP),BX
    

    Whereas the slice version is computing exclusively on registers after loading once from memory:

    LEAQ    (DX)(SI*1),BX
    

    This is not conclusive but probably the cause. Reason being that both methods are otherwise virtually identical. One other notable detail is that the array version calls into runtime.duffcopy, which is a quite long assembly routine, whereas the slice version doesn't.

    0 讨论(0)
  • 2020-12-14 03:45

    Go version 1.8 can eliminate some range checks so the difference got bigger.

    BenchmarkSliceGlobal-4 500000 3220 ns/op BenchmarkArrayGlobal-4 1000000 1287 ns/op BenchmarkSliceLocal-4 1000000 1267 ns/op BenchmarkArrayLocal-4 1000000 1301 ns/op

    For arrays I'd recommend to use sizes from powers of two and include a logical and operation. In that way you're sure the compiler eliminates the check. Thus var ga [1024]byte with ga[j & 1023].

    0 讨论(0)
提交回复
热议问题