HUH函数
假设没有前置/后继空格字符,仍然有几种方法可以断言字符串相等。其中一些是:strings.ToLower(..) 然后 ==strings.EqualFold(.., ..)cases#Lower 配对 ==cases#Fold 配对 ==以下是一些基本的基准测试结果(在这些测试中,strings.EqualFold(.., ..)似乎是性能最好的选择):goos: darwingoarch: amd64BenchmarkStringOps/both_strings_equal::equality_op-4 10000 182944 ns/opBenchmarkStringOps/both_strings_equal::strings_equal_fold-4 10000 114371 ns/opBenchmarkStringOps/both_strings_equal::fold_caser-4 10000 2599013 ns/opBenchmarkStringOps/both_strings_equal::lower_caser-4 10000 3592486 ns/opBenchmarkStringOps/one_string_in_caps::equality_op-4 10000 417780 ns/opBenchmarkStringOps/one_string_in_caps::strings_equal_fold-4 10000 153509 ns/opBenchmarkStringOps/one_string_in_caps::fold_caser-4 10000 3039782 ns/opBenchmarkStringOps/one_string_in_caps::lower_caser-4 10000 3861189 ns/opBenchmarkStringOps/weird_casing_situation::equality_op-4 10000 619104 ns/opBenchmarkStringOps/weird_casing_situation::strings_equal_fold-4 10000 148489 ns/opBenchmarkStringOps/weird_casing_situation::fold_caser-4 10000 3603943 ns/opBenchmarkStringOps/weird_casing_situation::lower_caser-4 10000 3637832 ns/op由于有很多选项,所以这里是生成基准的代码。package mainimport ( "fmt" "strings" "testing" "golang.org/x/text/cases" "golang.org/x/text/language")func BenchmarkStringOps(b *testing.B) { foldCaser := cases.Fold() lowerCaser := cases.Lower(language.English) tests := []struct{ description string first, second string }{ { description: "both strings equal", first: "aaaa", second: "aaaa", }, { description: "one string in caps", first: "aaaa", second: "AAAA", }, { description: "weird casing situation", first: "aAaA", second: "AaAa", }, } for _, tt := range tests { b.Run(fmt.Sprintf("%s::equality op", tt.description), func(b *testing.B) { for i := 0; i < b.N; i++ { benchmarkStringEqualsOperation(tt.first, tt.second, b) } }) b.Run(fmt.Sprintf("%s::strings equal fold", tt.description), func(b *testing.B) { for i := 0; i < b.N; i++ { benchmarkStringsEqualFold(tt.first, tt.second, b) } }) b.Run(fmt.Sprintf("%s::fold caser", tt.description), func(b *testing.B) { for i := 0; i < b.N; i++ { benchmarkStringsFoldCaser(tt.first, tt.second, foldCaser, b) } }) b.Run(fmt.Sprintf("%s::lower caser", tt.description), func(b *testing.B) { for i := 0; i < b.N; i++ { benchmarkStringsLowerCaser(tt.first, tt.second, lowerCaser, b) } }) }}func benchmarkStringEqualsOperation(first, second string, b *testing.B) { for n := 0; n < b.N; n++ { _ = strings.ToLower(first) == strings.ToLower(second) }}func benchmarkStringsEqualFold(first, second string, b *testing.B) { for n := 0; n < b.N; n++ { _ = strings.EqualFold(first, second) }}func benchmarkStringsFoldCaser(first, second string, caser cases.Caser, b *testing.B) { for n := 0; n < b.N; n++ { _ = caser.String(first) == caser.String(second) }}func benchmarkStringsLowerCaser(first, second string, caser cases.Caser, b *testing.B) { for n := 0; n < b.N; n++ { _ = caser.String(first) == caser.String(second) }}