<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] >= 'A' && s[i] <= 'Z' {
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] >= 'A' && s[i] <= 'Z' {
c *= 100
c += int64(s[i])
}
}
c = c % 31
return c
}
func BenchmarkLoop(b *testing.B) {
for i := 0; i < b.N; i++ {
loop("skhfakjsdfhaksaskdhskdjfaskhdsdkasdfasdfskdhf")
}
}
func BenchmarkLoop2(b *testing.B) {
for i := 0; i < b.N; i++ {
loop2("skhfakjsdfhaksaskdhskdjfaskhdsdkasdfasdfskdhf")
}
}
</code></pre>
<hr/>**评论:**<br/><br/>pappogeomys: <pre><p>Ranging over a string does need to interpret the string as runes. These loops don'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
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传