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

if len(mystring) > 0 { }

Or:

if mystring != "" { }

还是别的什么?


当前回答

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

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

其他回答

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

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

使用下面这样的函数会更简洁,更不容易出错:

func empty(s string) bool {
    return len(strings.TrimSpace(s)) == 0
}

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

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

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

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

https://godbolt.org/z/fib1x1

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

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 {

        }
    }
}