in golang, is there any performance difference between maps initialized using make vs {}

Issue

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)

Solution

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

Answered By – John Weldon

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.