Hacker News new | past | comments | ask | show | jobs | submit login
Benchmark of Golang slice initialization (Always use known capacity) (simon-frey.eu)
2 points by l1am0 on Aug 7, 2019 | hide | past | favorite | 2 comments



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...

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...

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 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


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




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: