What is the best way to test for an empty string in Go?

前端 未结 10 662
终归单人心
终归单人心 2021-01-29 20:26

Which method is best (more idomatic) for testing non-empty strings (in Go)?

if len(mystring) > 0 { }

Or:

if mystring != \"\"         


        
10条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-29 20:33

    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 {
    
            }
        }
    }
    

提交回复
热议问题