对于测试非空字符串(在Go中),哪种方法是最好的(最常用的)?

if len(mystring) > 0 { }

Or:

if mystring != "" { }

还是别的什么?


当前回答

到目前为止,Go编译器在这两种情况下生成相同的代码,所以这是一个品味问题。GCCGo确实会生成不同的代码,但几乎没有人使用它,所以我不担心这个问题。

https://godbolt.org/z/fib1x1

其他回答

假设空格和所有前导和后面的空格都应该被删除:

import "strings"
if len(strings.TrimSpace(s)) == 0 { ... }

因为: Len("") //为0 Len(" ") //一个空格为1 Len(" ") //两个空格为2

我认为最好的方法是与空白字符串进行比较

BenchmarkStringCheck1检查空字符串

BenchmarkStringCheck2检查len 0

我检查空字符串和非空字符串检查。您可以看到,使用空字符串进行检查更快。

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 {

        }
    }
}

这将比修整整个字符串的性能更好,因为您只需要检查至少一个存在的非空格字符

// Strempty checks whether string contains only whitespace or not
func Strempty(s string) bool {
    if len(s) == 0 {
        return true
    }

    r := []rune(s)
    l := len(r)

    for l > 0 {
        l--
        if !unicode.IsSpace(r[l]) {
            return false
        }
    }

    return true
}

根据官方的指导方针,从性能的角度来看,它们看起来是相等的(ANisus的答案),s != ""由于语法优势,将会更好。如果变量不是字符串,S != ""将在编译时失败,而len(S) == 0将通过其他几种数据类型。

这似乎是不成熟的微优化。编译器可以为这两种情况或至少为这两种情况生成相同的代码

if len(s) != 0 { ... }

and

if s != "" { ... }

因为语义显然是相等的。