Suboptimal optimizer?

blov · · 312 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hi, I just discovered a possible regression. Both loops does the same ting, but one is cast to []byte before looping. I see no reason why the string loop is so much slower, given that there is no unicode/rune interpretation or anything, just a string of bytes. Love to hear from the community if this is expected behaviour....</p> <p>I ran this on 1.8rc2:</p> <pre><code>go test -bench . BenchmarkLoop-8 30000000 47.8 ns/op BenchmarkLoop2-8 50000000 32.8 ns/op func loop(s string) int64 { c := int64(0) for i := range s { if s[i] &gt;= &#39;A&#39; &amp;&amp; s[i] &lt;= &#39;Z&#39; { c *= 100 c += int64(s[i]) } } c = c % 31 return c } func loop2(s string) int64 { c := int64(0) for i := range []byte(s) { if s[i] &gt;= &#39;A&#39; &amp;&amp; s[i] &lt;= &#39;Z&#39; { c *= 100 c += int64(s[i]) } } c = c % 31 return c } func BenchmarkLoop(b *testing.B) { for i := 0; i &lt; b.N; i++ { loop(&#34;skhfakjsdfhaksaskdhskdjfaskhdsdkasdfasdfskdhf&#34;) } } func BenchmarkLoop2(b *testing.B) { for i := 0; i &lt; b.N; i++ { loop2(&#34;skhfakjsdfhaksaskdhskdjfaskhdsdkasdfasdfskdhf&#34;) } } </code></pre> <hr/>**评论:**<br/><br/>pappogeomys: <pre><p>Ranging over a string does need to interpret the string as runes. These loops don&#39;t do the same thing. </p></pre>FantomLancer: <pre><p>interesting, I was sure they string[i] vs byte[i] always would return the same value.</p></pre>Epolevne: <pre><p>They will, but using range on a string will return indices of runes. So for a string of multi-byte runes range may send back indices 0, 3, 6, etc. </p></pre>FantomLancer: <pre><p>It makes a lot of sense now. I obviously had the wrong idea of how that looping works! Thanks for the quick and great help!</p></pre>funny_falcon: <pre><p>Offtopic: what your function should do?</p></pre>

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

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