Skip to content

Instantly share code, notes, and snippets.

@lummie
Created June 8, 2017 07:53
Show Gist options
  • Save lummie/bbcc0ede9c13cde88cf0e9b65522b271 to your computer and use it in GitHub Desktop.
Save lummie/bbcc0ede9c13cde88cf0e9b65522b271 to your computer and use it in GitHub Desktop.
Golang Test Empty string vs len
package string_test
import "testing"
func Benchmark_StringNotEqual(b *testing.B) {
z := ""
i := 0
for i:= 0; i<b.N; i++ {
if z != "" {
i++
}
}
print(i)
}
func Benchmark_LenGreater(b *testing.B) {
z := ""
i := 0
for i:= 0; i<b.N; i++ {
if len(z) != 0 {
i++
}
}
print(i)
}
func Benchmark_StringEqual(b *testing.B) {
z := ""
i := 0
for i:= 0; i<b.N; i++ {
if z == "" {
i++
}
}
print(i)
}
func Benchmark_LenEqual(b *testing.B) {
z := ""
i := 0
for i:= 0; i<b.N; i++ {
if len(z) == 0 {
i++
}
}
print(i)
}
/*
Output
2000000000 0.24 ns/op Benchmark_StringNotEqual
2000000000 0.24 ns/op Benchmark_LenGreater
2000000000 0.13 ns/op Benchmark_StringEqual
2000000000 0.14 ns/op Benchmark_LenEqual
PASS
As you can see there is not a lot in it, however I was surprised the time difference between == and !=
*/
@ValentinMouret
Copy link

Really nice, thanks! :)

@jtackaberry
Copy link

This test looks flawed to me. When the condition evaluates true you're incrementing the loop variable, thereby decreasing the number of iterations.

When you fix this, all these options perform quite similarly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment