dongyue4964 2016-07-11 20:41
浏览 308
已采纳

在golang中,使用make与{}初始化的地图之间在性能上有什么区别

as we know there are two ways to initialize a map (as listed below). I'm wondering if there is any performance difference between the two approaches.

var myMap map[string]int

then

myMap = map[string]int{}

vs

myMap = make(map[string]int)
  • 写回答

2条回答 默认 最新

  • duanpang5583 2016-07-12 02:16
    关注

    On my machine they appear to be about equivalent.

    You can easily make a benchmark test to compare. For example:

    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)
    }
    

    Which on 3 different runs yielded results that are close enough to be insignificant:

    First Run

    $ 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
    

    Second Run

    $ 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
    

    Third Run

    $ 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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败