我们知道有两种方法可以初始化地图(如下所示).我想知道这两种方法之间是否存在任何性能差异.
var myMap map[string]int
然后
myMap = map[string]int{}
VS
myMap = make(map[string]int)
在我的机器上,它们看起来大致相当.
原文链接:https://www.f2er.com/go/242062.html您可以轻松地进行基准测试以进行比较.例如:
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