不要使用 +
和 fmt.Sprintf
操作字符串,虽然很方便,但是真的很慢!
我们要使用 bytes.NewBufferString
进行处理。
基准测试如下:
func BenchmarkStringOperation1(b *testing.B) {b.ResetTimer()str := ""for i := 0; i < b.N; i++ {str += "golang"}}// 输出goos: darwingoarch: amd64pkg: demo/stringoperationcpu: Intel(R) Core(TM) i7-8700B CPU @ 3.20GHzBenchmarkStringOperation1BenchmarkStringOperation1-12 353318 114135 ns/opPASSProcess finished with the exit code 0
func BenchmarkStringOperation2(b *testing.B) {b.ResetTimer()str := ""for i := 0; i < b.N; i++ {str = fmt.Sprintf("%s%s", str, "golang")}}// 输出goos: darwingoarch: amd64pkg: demo/stringoperationcpu: Intel(R) Core(TM) i7-8700B CPU @ 3.20GHzBenchmarkStringOperation2BenchmarkStringOperation2-12 280140 214098 ns/opPASSProcess finished with the exit code 0
func BenchmarkStringOperation3(b *testing.B) {b.ResetTimer()strBuf := bytes.NewBufferString("")for i := 0; i < b.N; i++ {strBuf.WriteString("golang")}}// 输出goos: darwingoarch: amd64pkg: demo/stringoperationcpu: Intel(R) Core(TM) i7-8700B CPU @ 3.20GHzBenchmarkStringOperation3BenchmarkStringOperation3-12 161292136 8.582 ns/opPASSProcess finished with the exit code 0
对于固定字段的键值对,不要使用 map[string]interface{}
!
我们要使用临时 Struct
。
基准测试如下:
func BenchmarkStructOperation1(b *testing.B) {b.ResetTimer()for i := 0; i < b.N; i++ {var demo = map[string]interface{}{}demo["Name"] = "Tom"demo["Age"] = 30}}// 输出goos: darwingoarch: amd64pkg: demo/structoperationcpu: Intel(R) Core(TM) i7-8700B CPU @ 3.20GHzBenchmarkStructOperation1BenchmarkStructOperation1-12 43300134 27.97 ns/opPASSProcess finished with the exit code 0
func BenchmarkStructOperation2(b *testing.B) {b.ResetTimer()for i := 0; i < b.N; i++ {var demo struct {Name stringAge int}demo.Name = "Tom"demo.Age = 30}}// 输出oos: darwingoarch: amd64pkg: demo/structoperationcpu: Intel(R) Core(TM) i7-8700B CPU @ 3.20GHzBenchmarkStructOperation2BenchmarkStructOperation2-12 1000000000 0.2388 ns/opPASSProcess finished with the exit code 0
你有类似这样的注意点吗,欢迎留言~
下面推荐阅读的这几篇文章也是关于开发中需要知道的小技术点,更多技术细节和代码讨论,可以加入到我的星球。