Which method is best (more idomatic) for testing non-empty strings (in Go)?
if len(mystring) > 0 { }
Or:
if mystring != \"\"
I think the best way is to compare with blank string
BenchmarkStringCheck1 is checking with blank string
BenchmarkStringCheck2 is checking with len zero
I check with the empty and non-empty string checking. You can see that checking with a blank string is faster.
BenchmarkStringCheck1-4 2000000000 0.29 ns/op 0 B/op 0 allocs/op
BenchmarkStringCheck1-4 2000000000 0.30 ns/op 0 B/op 0 allocs/op
BenchmarkStringCheck2-4 2000000000 0.30 ns/op 0 B/op 0 allocs/op
BenchmarkStringCheck2-4 2000000000 0.31 ns/op 0 B/op 0 allocs/op
Code
func BenchmarkStringCheck1(b *testing.B) {
s := "Hello"
b.ResetTimer()
for n := 0; n < b.N; n++ {
if s == "" {
}
}
}
func BenchmarkStringCheck2(b *testing.B) {
s := "Hello"
b.ResetTimer()
for n := 0; n < b.N; n++ {
if len(s) == 0 {
}
}
}