What's the fastest way to convert base-10 64 bit signed integer to []byte?

agolangf · · 396 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I want to use it to persist many counters on the disk.</p> <hr/>**评论:**<br/><br/>TheMerovius: <pre><pre><code>n, _ := strconv.ParseInt(&#34;12345678901234&#34;, 10, 64) b := make([]byte, 8) binary.LittleEndian.PutUint64(b, n) </code></pre></pre>andreasblixt: <pre><p>Note that you&#39;d have to turn the <code>int64</code> into a <code>uint64</code> before <code>PutUint64</code> will work.</p> <p>But – if writing to disk anyway:</p> <pre><code>n, _ := strconv.ParseInt(&#34;12345678901234&#34;, 10, 64) binary.Write(w, binary.LittleEndian, n) </code></pre></pre>TheMerovius: <pre><blockquote> <p>Note that you&#39;d have to turn the int64 into a uint64 before PutUint64 will work.</p> </blockquote> <p>Ah, right, forgot that part. But doesn&#39;t matter, just convert, it&#39;ll do the right thing.</p> <blockquote> <p>But – if writing to disk anyway:</p> </blockquote> <p><code>binary.Write</code> uses reflection, so I avoided it intentionally due to the &#34;fastest way&#34; in the question (whether this actually needs to be the fastest way is a different question - probably not).</p></pre>andreasblixt: <pre><p>I would measure before deciding which way is faster. For example, if the <code>b</code> slice is recreated for every value instead of being reused, then it might very well be slower than <code>binary.Write</code>. And if done perfectly (by which I mean writing more complex code), it might still only be faster on the order of nanoseconds per value, at which point the disk writes will overweigh the speed difference so much it might not even be measurable.</p></pre>dcormier: <pre><p>Or, if you&#39;re not writing to disk:</p> <pre><code>n, _ := strconv.ParseInt(&#34;12345678901234&#34;, 10, 64) buf := &amp;bytes.Buffer{} binary.Write(buf, binary.LittleEndian, n) // buf.Bytes() has your []byte </code></pre></pre>drvd: <pre><pre><code>func convert(s string) []byte {return nil} </code></pre> <p>Is the fastest way. Albeit not the most correct one. (Paraphrasing Russ).</p> <pre><code>func convert(s string) []byte {return []byte(s)} </code></pre> <p>Is an other candidate which turns a base-10 64 bit signed integer string to a byte slice. It is very fast and correct and converts any string to a byte slice.</p> <p>Your use case seems like speed of conversion won&#39;t be the problem: Writing to disk is presumably slower than strconv + bitfidling.</p></pre>

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

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