Why have arrays in Go?

前端 未结 4 681
北海茫月
北海茫月 2020-11-27 05:46

I understand the difference between arrays and slices in Go. But what I don\'t understand is why it is helpful to have arrays at all. Why is it helpful that an array type de

4条回答
  •  庸人自扰
    2020-11-27 06:24

    Arrays are values, and it is often useful to have a value instead of a pointer.

    Values can be compared, hence you can use arrays as map keys.

    Values are always initialized, so there's you don't need to initialize, or make them like you do with a slice.

    Arrays give you better control of memory layout, where as you can't allocate space directly in a struct with a slice, you can with an array:

    type Foo struct {
        buf [64]byte
    }
    

    Here, a Foo value will contains a 64 byte value, rather than a slice header which needs to be separately initialized. Arrays are also used to pad structs to match alignment when interoperating with C code and to prevent false sharing for better cache performance.

    Another aspect for improved performance is that you can better define memory layout than with slices, because data locality can have a very big impact on memory intensive calculations. Dereferencing a pointer can take considerable time compared to the operations being performed on the data, and copying values smaller than a cache line incurs very little cost, so performance critical code often uses arrays for that reason alone.

提交回复
热议问题