Created
June 8, 2017 07:53
-
-
Save lummie/bbcc0ede9c13cde88cf0e9b65522b271 to your computer and use it in GitHub Desktop.
Golang Test Empty string vs len
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 != | |
*/ |
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
Really nice, thanks! :)