Let me quickly point out that your logic is inverted in the second code snippet because you break on the condition. That is most likely the reason for the difference. I guess the second example exits on the first iteration.

for pos := 0; true; pos++ {
   if pos < suffixLen && pos < previousSuffixLen {
     continue
   }
   break
}

On 22.06.20 14:15, Yonatan Ben-Nes wrote:
Hi,

I'm encountering a weird issue which I fail to explain. It boils down to 2 almost identical functions which give wildly different benchmark results.

The difference between the functions is that at the slow func there is a for loop like this:
for pos := 0; pos < suffixLen && pos < previousSuffixLen; pos++ {
}

While at the fast func the loop is like this:
for pos := 0; true; pos++ {
if pos < suffixLen && pos < previousSuffixLen {
break
}
}
* do note that the check at both versions is the same.

Other than that the functions are identical but when I benchmark them I get:
$ go test -bench=Weird .
goos: linux
goarch: amd64
BenchmarkWeirdFast-4 280394 3602 ns/op
BenchmarkWeirdSlow-4 1866 618953 ns/op

It's extra weird since getting the condition check into the loop should be the slower form, or at least that what I intuitively thought.

Also, the extra time cost is divided between the loop section and an append function call which run immediately at the start of the function and is not connected in any way to the for loop. And it's extra weird as the append cost also get smaller if instead of reading the test text from a file I just declare a string variable with the same text for the benchmark (mind you that I b.ResetTimer() after doing either of those options).

I attached the files to this message as they will make everything more clear and I also added comments describing what happen at the right points.

I'm using Ubuntu 18.04 and go is version 1.14.2, and I also checked it on a GCP compute engine and got the same results.

Any thoughts will be much appreciated as I'm totally confused here! :)

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com <mailto:golang-nuts+unsubscr...@googlegroups.com>. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/3cf40b00-96ec-42a6-8093-7f1c27bfd93fn%40googlegroups.com <https://groups.google.com/d/msgid/golang-nuts/3cf40b00-96ec-42a6-8093-7f1c27bfd93fn%40googlegroups.com?utm_medium=email&utm_source=footer>.

--
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/d661fbea-ca23-dd55-0f45-b3c10cefd9aa%40mb0.org.

Reply via email to