TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Benchmark of Golang slice initialization (Always use known capacity)

2 pointsby l1am0almost 6 years ago

1 comment

martischalmost 6 years ago
I think this part &quot;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. &quot; is not what the Go gc implementation currently actually does.<p>Copied from reddit: <a href="https:&#x2F;&#x2F;www.reddit.com&#x2F;r&#x2F;golang&#x2F;comments&#x2F;cn2jdh&#x2F;benchmark_of_golang_slice_initialization_always&#x2F;" rel="nofollow">https:&#x2F;&#x2F;www.reddit.com&#x2F;r&#x2F;golang&#x2F;comments&#x2F;cn2jdh&#x2F;benchmark_of...</a><p>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&#x2F;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. <a href="https:&#x2F;&#x2F;github.com&#x2F;golang&#x2F;go&#x2F;blob&#x2F;e37a1b1ca6afcbe3b02d2dfd599ad1d3d926ec34&#x2F;src&#x2F;runtime&#x2F;slice.go#L49" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;golang&#x2F;go&#x2F;blob&#x2F;e37a1b1ca6afcbe3b02d2dfd59...</a><p>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: <a href="https:&#x2F;&#x2F;godbolt.org&#x2F;z&#x2F;wRuF5z" rel="nofollow">https:&#x2F;&#x2F;godbolt.org&#x2F;z&#x2F;wRuF5z</a> while for size = 100000 the backing array is heap allocated and zeroed as part of the runtime.makeslice call.<p>There is a optimization fusing make+copy (to avoid the memclr) in the pipeline for go1.14 but this would not trigger here either.<a href="https:&#x2F;&#x2F;go-review.googlesource.com&#x2F;c&#x2F;go&#x2F;+&#x2F;146719" rel="nofollow">https:&#x2F;&#x2F;go-review.googlesource.com&#x2F;c&#x2F;go&#x2F;+&#x2F;146719</a>
评论 #20633183 未加载