What are allocations and why do I need to know about them?

xuanbao · · 563 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I&#39;ve seen a lot of talk lately about allocations. Specifically about recent changes in the GC and also in <a href="http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/index.html#string_byte_slice_conv">string to byte conversions</a>. I know they are bad because they are &#34;ineffieient usage of memory&#34;; my words, not something I&#39;ve read. </p> <p>Can someone elaborate on what is happening behind the scenes and what are some red flags I should look out for?</p> <hr/>**评论:**<br/><br/>calebdoxsey: <pre><p>Simplistically when you create something in Go it will automatically allocate enough memory for that object. For example:</p> <pre><code> x := make([]byte, 1000) </code></pre> <p>Will allocate 1000 bytes of memory. Eventually when <code>x</code> is no longer used it will be freed by the garbage collector. A common pattern in Go is to append to a slice:</p> <pre><code> xs := []byte{} for _, b := range someBytes { xs = append(xs, b) } </code></pre> <p>The way this works is that every slice has a length and a capacity. <code>append</code> will just put the byte in the next element of the array until the capacity is reached. At that point it has to create a brand new array and copy over all the old values.</p> <p>If we had created the slice with an initial, larger capacity:</p> <pre><code>xs := make([]byte, 0, len(someBytes)) </code></pre> <p>We could avoid all the allocations (meaning creating a new slice) and copies.</p> <p>This comes down to optimization, but the design of the language is such that it&#39;s not the main thing you should be thinking about. The whole point of garbage collection is that managing memory is error prone and tedious, so a lot of work is going into making the garbage collector as clever as possible.</p> <p>I&#39;m not sure there are any red-flags here, outside of standard programming ones (code that would be bad in any language). If you have a program where such optimizations are necessary there are some strategies you could use - like the pool in sync - but I&#39;m not sure how often you would need to actually use those strategies.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

563 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传