<p>Can someone explain this:</p>
<p><a href="http://i.imgur.com/nSxBSF7.png" rel="nofollow">http://i.imgur.com/nSxBSF7.png</a></p>
<p>Why is the capacity on the last slice 6 instead of 5?</p>
<hr/>**评论:**<br/><br/>dbud: <pre><p>Go slices grow with extra capacity to avoid a constant reallocation and copy of memory.</p>
<p>Not sure what the exact aglo is, but it's probably not crazy different than:</p>
<p>Here's an example on play: <a href="http://play.golang.org/p/FcRm_2gGTf" rel="nofollow">http://play.golang.org/p/FcRm_2gGTf</a></p>
<p>package main</p>
<pre><code>import "fmt"
func main() {
orig := make([]bool, 2)
next := make([]bool, len(orig), int((float64(cap(orig)+4))*1.15))
fmt.Println(len(orig), cap(orig), len(next), cap(next))
}
</code></pre></pre>jahayhurst: <pre><p>You're on this page, correct?</p>
<p><a href="https://tour.golang.org/moretypes/12" rel="nofollow">https://tour.golang.org/moretypes/12</a></p>
<p>Let's say yes. Check this out:</p>
<p><a href="https://play.golang.org/p/SA5l2Us-q4" rel="nofollow">https://play.golang.org/p/SA5l2Us-q4</a></p>
<p>capacity doesn't grow constantly.</p></pre>jahayhurst: <pre><p>btw, doing some dumb testing (and copying that stuff over and over) it looks like the size of the array is just doubled if it's not big enough?</p>
<p>w/e, it doesn't matter - it works no matter what for what I always need :-)</p></pre>gergo254: <pre><blockquote>
<p>the size of the array is just doubled if it's not big enough</p>
</blockquote>
<p>Yeah, that's how that works. :)</p></pre>afghanPower: <pre><p>Thanks. </p></pre>itsamemmario: <pre><p>Rob Pike wrote a great article on "the mechanics of append" and it's well worth the read. The exact answer is near the end of article
<a href="https://blog.golang.org/slices" rel="nofollow">https://blog.golang.org/slices</a>
EDIT: just to elaborate:
The reason why it doubles size is because memory allocation is an expensive operation. Making an array bigger means allocating a bigger second array in the memory and copying all values from the first into it. If you this every time you add and element to your array, you slow down your program considerably. </p></pre>afghanPower: <pre><p>I actually did this on a java assignment not too long ago. Thanks for taking time to answer ;)</p></pre>Talindras: <pre><p>You're confusing used space and allocated space. The slice has allocated enough memory to store 6 elements, but currently only stores 5.</p></pre>afghanPower: <pre><p>I already understood the meaning of capacity. Like you can make a empty (len = 0) slice with a capacity of say 5. I just found it weird that when the len was 2, cap was also 2. Suddenly at len = 5, cap was 6.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传