
Benchmark of Golang slice initialization (Always use known capacity) - l1am0
https://blog.simon-frey.eu/known-length-slice-initialization-speed-golang-benchmark-wednesday
======
martisch
I think this part "Step 1) is not needed with the append approach, as we just
reserve a memory location but the previous values stay there until we write
them in step 2. " is not what the Go gc implementation currently actually
does.

Copied from reddit:
[https://www.reddit.com/r/golang/comments/cn2jdh/benchmark_of...](https://www.reddit.com/r/golang/comments/cn2jdh/benchmark_of_golang_slice_initialization_always/)

Currently make (runtime.makeslice or runtime.mallocgc or duffzero as part of
stack allocation) always zeroes the backing array of slice regardless if the
element is written to directly or append to the slice. Not requiring the
memclr/zeroing would need a prove pass that proves that before the loop
finishes noone can observe the uninitialized value by e.g. re-slicing. Which
in general when e.g. interfaces and plugins are involved wont be possible to
prove. In the case of pointers the memclr is also not avoidable since the
garbage collector might scan that part of the memory (if its heap allocated)
any time even while the loop is running.
[https://github.com/golang/go/blob/e37a1b1ca6afcbe3b02d2dfd59...](https://github.com/golang/go/blob/e37a1b1ca6afcbe3b02d2dfd599ad1d3d926ec34/src/runtime/slice.go#L49)

There could be effects observed due to the difference of having small slices
allocated on the stack vs on the heap and differing zero techniques. E.g. for
size = 100 there is a jump to duffzero that clears the stack space for the
backing array of the slice:
[https://godbolt.org/z/wRuF5z](https://godbolt.org/z/wRuF5z) while for size =
100000 the backing array is heap allocated and zeroed as part of the
runtime.makeslice call.

There is a optimization fusing make+copy (to avoid the memclr) in the pipeline
for go1.14 but this would not trigger here either.[https://go-
review.googlesource.com/c/go/+/146719](https://go-
review.googlesource.com/c/go/+/146719)

~~~
l1am0
Awesome! Will give all the resources a look and see how to improve the article

