我们知道有两种初始化 map 的方法(如下所列)。我想知道这两种方法之间是否存在任何性能差异。
var myMap map[string]int
然后
myMap = map[string]int{}
对比
myMap = make(map[string]int)
最佳答案
在我的机器上,它们看起来差不多。
您可以轻松地进行基准测试进行比较。例如:
package bench
import "testing"
var result map[string]int
func BenchmarkMakeLiteral(b *testing.B) {
var m map[string]int
for n := 0; n < b.N; n++ {
m = InitMapLiteral()
}
result = m
}
func BenchmarkMakeMake(b *testing.B) {
var m map[string]int
for n := 0; n < b.N; n++ {
m = InitMapMake()
}
result = m
}
func InitMapLiteral() map[string]int {
return map[string]int{}
}
func InitMapMake() map[string]int {
return make(map[string]int)
}
在 3 次不同的运行中产生的结果非常接近以至于可以忽略不计:
首次运行
$ go test -bench=.
testing: warning: no tests to run
PASS
BenchmarkMakeLiteral-8 10000000 160 ns/op
BenchmarkMakeMake-8 10000000 171 ns/op
ok github.com/johnweldon/bench 3.664s
第二次运行
$ go test -bench=.
testing: warning: no tests to run
PASS
BenchmarkMakeLiteral-8 10000000 182 ns/op
BenchmarkMakeMake-8 10000000 173 ns/op
ok github.com/johnweldon/bench 3.945s
第三轮
$ go test -bench=.
testing: warning: no tests to run
PASS
BenchmarkMakeLiteral-8 10000000 170 ns/op
BenchmarkMakeMake-8 10000000 170 ns/op
ok github.com/johnweldon/bench 3.751s
关于performance - 在 golang 中,使用 make 与 {} 初始化的 map 之间是否存在任何性能差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38315860/