performance - 在 golang 中,使用 make 与 {} 初始化的 map 之间是否存在任何性能差异

标签 performance go

我们知道有两种初始化 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/

相关文章:

android - 如何在后台线程上运行 ListenableWorker 工作?

java - 泛型对执行时间的影响

go - os.PathError 未实现错误

string - 在 Golang 中将字符串传递给准备好的语句

go - 在 protobuf 中封装 float64 的包

linux - Linux时分进程还是线程

performance - OpenCL 如何分配工作项?

profiling - Go 分析器的输出令人困惑(而且不正确?)

go - Golang的net/rpc包和gRPC框架有什么区别?

jquery - 加载html,然后在Jquery中使用Ajax加载图像