对于测试非空字符串(在Go中),哪种方法是最好的(最常用的)?
if len(mystring) > 0 { }
Or:
if mystring != "" { }
还是别的什么?
对于测试非空字符串(在Go中),哪种方法是最好的(最常用的)?
if len(mystring) > 0 { }
Or:
if mystring != "" { }
还是别的什么?
当前回答
这似乎是不成熟的微优化。编译器可以为这两种情况或至少为这两种情况生成相同的代码
if len(s) != 0 { ... }
and
if s != "" { ... }
因为语义显然是相等的。
其他回答
我认为最好的方法是与空白字符串进行比较
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
}
这两种样式都在Go的标准库中使用。
if len(s) > 0 { ... }
可以在strconv包中找到:http://golang.org/src/pkg/strconv/atoi.go
if s != "" { ... }
可以在encoding/json包中找到:http://golang.org/src/pkg/encoding/json/encode.go
两者都是惯用的,而且都足够清楚。这更多的是个人品味和清晰度的问题。
Russ Cox在golang-nuts的帖子中写道:
使代码清晰的那个。 如果我要查看元素x,我通常会写 len(s) >x,即使x == 0,但如果我关心 "是这个特定的字符串"我倾向于写s == "" 假设一个成熟的编译器会编译是合理的 Len (s) == 0和s == ""变成了同样高效的代码。 ... 使代码清晰。
正如Timmmm的回答所指出的,在这两种情况下,Go编译器确实生成了相同的代码。
检查长度是一个很好的答案,但您也可以解释一个“空”字符串,它也只是空白。严格来说不是空的,但如果你愿意检查:
package main
import (
"fmt"
"strings"
)
func main() {
stringOne := "merpflakes"
stringTwo := " "
stringThree := ""
if len(strings.TrimSpace(stringOne)) == 0 {
fmt.Println("String is empty!")
}
if len(strings.TrimSpace(stringTwo)) == 0 {
fmt.Println("String two is empty!")
}
if len(stringTwo) == 0 {
fmt.Println("String two is still empty!")
}
if len(strings.TrimSpace(stringThree)) == 0 {
fmt.Println("String three is empty!")
}
}
到目前为止,Go编译器在这两种情况下生成相同的代码,所以这是一个品味问题。GCCGo确实会生成不同的代码,但几乎没有人使用它,所以我不担心这个问题。
https://godbolt.org/z/fib1x1