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! :)