分享两个在开发中需注意的小点

文章目录:

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

    • +

    • fmt.Sprintf

    • bytes.NewBufferString

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

    • map[string]interface{}

    • 临时 Struct

  • 小结

    • 推荐阅读

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

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

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

基准测试如下:

+

func BenchmarkStringOperation1(b *testing.B)  {
 b.ResetTimer()
 str := ""
 for i := 0; i < b.N; i++ {
  str += "golang"
 }
}

// 输出
goos: darwin
goarch: amd64
pkg: demo/stringoperation
cpu: Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz
BenchmarkStringOperation1
BenchmarkStringOperation1-12       353318     114135 ns/op
PASS

Process finished with the exit code 0

fmt.Sprintf

func BenchmarkStringOperation2(b *testing.B)  {
 b.ResetTimer()
 str := ""
 for i := 0; i < b.N; i++ {
  str = fmt.Sprintf("%s%s", str, "golang")
 }
}

// 输出
goos: darwin
goarch: amd64
pkg: demo/stringoperation
cpu: Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz
BenchmarkStringOperation2
BenchmarkStringOperation2-12       280140     214098 ns/op
PASS

Process finished with the exit code 0

bytes.NewBufferString

func BenchmarkStringOperation3(b *testing.B)  {
 b.ResetTimer()
 strBuf := bytes.NewBufferString("")
 for i := 0; i < b.N; i++ {
  strBuf.WriteString("golang")
 }
}

// 输出
goos: darwin
goarch: amd64
pkg: demo/stringoperation
cpu: Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz
BenchmarkStringOperation3
BenchmarkStringOperation3-12     161292136          8.582 ns/op
PASS

Process finished with the exit code 0

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

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

我们要使用临时 Struct

基准测试如下:

map[string]interface{}

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: darwin
goarch: amd64
pkg: demo/structoperation
cpu: Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz
BenchmarkStructOperation1
BenchmarkStructOperation1-12     43300134         27.97 ns/op
PASS

Process finished with the exit code 0

临时 Struct

func BenchmarkStructOperation2(b *testing.B) {
 b.ResetTimer()
 for i := 0; i < b.N; i++ {
  var demo struct {
   Name string
   Age  int
  }
  demo.Name = "Tom"
  demo.Age = 30
 }
}

// 输出
oos: darwin
goarch: amd64
pkg: demo/structoperation
cpu: Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz
BenchmarkStructOperation2
BenchmarkStructOperation2-12     1000000000          0.2388 ns/op
PASS

Process finished with the exit code 0

小结

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

 

分享两个在开发中需注意的小点

上一篇:sscanf和sprintf的用法


下一篇:嵌入式中sprintf %f 失效问题解决