不要使用 + 和 fmt.Sprintf 操作字符串

不要使用 +fmt.Sprintf 操作字符串,虽然很方便,但是真的很慢!

我们要使用 bytes.NewBufferString 进行处理。

基准测试如下:

+

  1. func BenchmarkStringOperation1(b *testing.B) {
  2. b.ResetTimer()
  3. str := ""
  4. for i := 0; i < b.N; i++ {
  5. str += "golang"
  6. }
  7. }
  8. // 输出
  9. goos: darwin
  10. goarch: amd64
  11. pkg: demo/stringoperation
  12. cpu: Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz
  13. BenchmarkStringOperation1
  14. BenchmarkStringOperation1-12 353318 114135 ns/op
  15. PASS
  16. Process finished with the exit code 0

fmt.Sprintf

  1. func BenchmarkStringOperation2(b *testing.B) {
  2. b.ResetTimer()
  3. str := ""
  4. for i := 0; i < b.N; i++ {
  5. str = fmt.Sprintf("%s%s", str, "golang")
  6. }
  7. }
  8. // 输出
  9. goos: darwin
  10. goarch: amd64
  11. pkg: demo/stringoperation
  12. cpu: Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz
  13. BenchmarkStringOperation2
  14. BenchmarkStringOperation2-12 280140 214098 ns/op
  15. PASS
  16. Process finished with the exit code 0

bytes.NewBufferString

  1. func BenchmarkStringOperation3(b *testing.B) {
  2. b.ResetTimer()
  3. strBuf := bytes.NewBufferString("")
  4. for i := 0; i < b.N; i++ {
  5. strBuf.WriteString("golang")
  6. }
  7. }
  8. // 输出
  9. goos: darwin
  10. goarch: amd64
  11. pkg: demo/stringoperation
  12. cpu: Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz
  13. BenchmarkStringOperation3
  14. BenchmarkStringOperation3-12 161292136 8.582 ns/op
  15. PASS
  16. Process finished with the exit code 0

对于固定字段的键值对,不要使用 map[string]interface{}

对于固定字段的键值对,不要使用 map[string]interface{}!

我们要使用临时 Struct

基准测试如下:

map[string]interface{}

  1. func BenchmarkStructOperation1(b *testing.B) {
  2. b.ResetTimer()
  3. for i := 0; i < b.N; i++ {
  4. var demo = map[string]interface{}{}
  5. demo["Name"] = "Tom"
  6. demo["Age"] = 30
  7. }
  8. }
  9. // 输出
  10. goos: darwin
  11. goarch: amd64
  12. pkg: demo/structoperation
  13. cpu: Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz
  14. BenchmarkStructOperation1
  15. BenchmarkStructOperation1-12 43300134 27.97 ns/op
  16. PASS
  17. Process finished with the exit code 0

临时 Struct

  1. func BenchmarkStructOperation2(b *testing.B) {
  2. b.ResetTimer()
  3. for i := 0; i < b.N; i++ {
  4. var demo struct {
  5. Name string
  6. Age int
  7. }
  8. demo.Name = "Tom"
  9. demo.Age = 30
  10. }
  11. }
  12. // 输出
  13. oos: darwin
  14. goarch: amd64
  15. pkg: demo/structoperation
  16. cpu: Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz
  17. BenchmarkStructOperation2
  18. BenchmarkStructOperation2-12 1000000000 0.2388 ns/op
  19. PASS
  20. Process finished with the exit code 0

小结

你有类似这样的注意点吗,欢迎留言~

下面推荐阅读的这几篇文章也是关于开发中需要知道的小技术点,更多技术细节和代码讨论,可以加入到我的星球:https://t.zsxq.com/iIUVVnA

推荐阅读