没有什么比预先计算好的查找表更好的了,特别是如果它存储在一个切片或数组中(而不是在一个映射中),并且转换器为结果分配了一个大小合适的字节切片:
var byteBinaries [256][]byte
func init() {
for i := range byteBinaries {
byteBinaries[i] = []byte(fmt.Sprintf("%08b", i))
}
}
func strToBin(s string) string {
res := make([]byte, len(s)*8)
for i := len(s) - 1; i >= 0; i-- {
copy(res[i*8:], byteBinaries[s[i]])
}
return string(res)
}
测试它:
fmt.Println(strToBin("\x01\xff"))
输出(在Go Playground上试试):
0000000111111111
基准测试
让我们看看它能达到多快:
var texts = []string{
"\x00",
"123",
"1234567890",
"asdf;lkjasdf;lkjasdf;lkj108fhq098wf34",
}
func BenchmarkOrig(b *testing.B) {
for n := 0; n < b.N; n++ {
for _, t := range texts {
binConvertOrig(t)
}
}
}
func BenchmarkLookup(b *testing.B) {
for n := 0; n < b.N; n++ {
for _, t := range texts {
strToBin(t)
}
}
}
结果:
BenchmarkOrig-4 200000 8526 ns/op 2040 B/op 12 allocs/op
BenchmarkLookup-4 2000000 781 ns/op 880 B/op 8 allocs/op
查找版本 (strToBin()) 快 11 倍,并且使用更少的内存和分配。基本上它只对结果使用分配(这是不可避免的)。