In Go, to check if a string is empty this can be used:
len(str) == 0
or
len(str) < 1
or
str == ""
Basically is just a meter of choosing an operator ==
, <
, !=
, but in terms of performance wish option is better ?
My guess is that ==
just compares and don't iterate through the values like <
or either <==
could do, therefore wondering what is the best approach practice for this.
Since the empty string is the nil value of a string, you should compare against that.
str == ""
Checking variables against their nil values to see if they are empty is the Go way of doing this.
In terms of performance, there's no notable difference. Using len(str)
is a function call, so it should in theory be slower.
EDIT: Some evidence:
I benchmarked this code:
func BenchmarkNil(b *testing.B) {
str := "asd"
cnt := 0
for i := 0; i < b.N; i++ {
if str == "" {
cnt++
}
}
}
with the three different checks in the if-statement: str == ""
, len(str) == 0
and len(str) < 1
.
BenchmarkLenEq-8 2000000000 0.77 ns/op
BenchmarkLenLess-8 2000000000 0.76 ns/op
BenchmarkNil-8 2000000000 0.50 ns/op
For checking against an empty string (str := ""
instead of str := "asd"
), there is no measurable difference. Checking against a non-empty string takes more time, and there, the nil check is noticeably faster.
BenchmarkLenEq-8 2000000000 0.34 ns/op
BenchmarkLenLess-8 2000000000 0.33 ns/op
BenchmarkNil-8 2000000000 0.33 ns/op
EDIT2: The only thing you can do these days to be somewhat sure of how fast something is is to benchmark it. Modern CPU's are superscalar, so one clock cycle per instruction is simply not true anymore. The benchmark code comparing against the empty string ran at 2.94GHz (2.94*10^9 op/s) on my 4GHz 6700k, which is less than two clock cycles per loop iteration. The nil check against the non-empty string ran at 2GHz (2*10^9 op/s) on the same CPU.
This means 2 cpu cycles per loop iteration on the nil check, and 3 on the len check, or a single instruction per loop iteration on the check against the empty string.