对于测试非空字符串(在Go中)哪种方法最好(更像是idomatic)?
if len(mystring) > 0 { }
要么:
if mystring != "" { }
或者是其他东西?
两种样式都在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 thread写道:
使代码清晰的那个。 如果我要查看元素x,我通常会写 len(s)> x,即使对于x == 0,但是如果我关心的话 “这是这个特定的字符串”我倾向于写s ==“”。
假设成熟的编译器将编译是合理的 len(s)== 0和s ==“”进入相同,有效的代码。 现在6g等将s ==“”编译成函数调用 虽然len(s)== 0不是,但那已经在我的待办事项清单上修复了。
使代码清晰。
这似乎是过早的微观优化。编译器可以自由地为两种情况生成相同的代码,或至少为这两种情况生成相同的代码
if len(s) != 0 { ... }
和
if s != "" { ... }
因为语义明显相等。
检查长度是一个很好的答案,但您也可以考虑一个“空”字符串,它也只是空格。不是“技术上”空的,但如果你想检查:
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!")
}
}
假设应删除空格和所有前导和尾随空格:
import "strings"
if len(strings.TrimSpace(s)) == 0 { ... }
因为:
len("") // is 0
len(" ") // one empty space is 1
len(" ") // two empty spaces is 2
截至目前,Go编译器在两种情况下都生成相同的代码,因此这是一个品味问题。 GCCGo会生成不同的代码,但几乎没有人使用它,所以我不担心。
使用类似下面的函数会更干净,更不容易出错:
func empty(s string) bool {
return len(strings.TrimSpace(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
}
我认为最好的方法是与空白字符串进行比较
BenchmarkStringCheck1正在检查空字符串
BenchmarkStringCheck2正在使用len零进行检查
我检查空和非空字符串检查。您可以看到使用空白字符串进行检查更快。
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
码
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 {
}
}
}