Home >Backend Development >Golang >Is There a Performance Difference Between Using `{}` and `make()` to Initialize Maps in Go?
Map Initialization in Go: make vs. {}
In Go, there are two common methods for initializing maps: using {} or make(). While they both result in an empty map, there is a question as to whether there is any performance difference between the two approaches.
To investigate this, let's create a benchmark test to compare the two initialization techniques:
<code class="go">package main 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 = map[string]int{} } result = m } func BenchmarkMakeMake(b *testing.B) { var m map[string]int for n := 0; n < b.N; n++ { m = make(map[string]int) } result = m } func main() { testing.Benchmark(BenchmarkMakeLiteral) testing.Benchmark(BenchmarkMakeMake) }</code>
Running the benchmark test on different machines shows consistent results, indicating that there is no significant performance difference between the two initialization methods. Both {} and make() result in nearly identical execution times.
In conclusion, while the {} and make() methods both produce an empty map, there is no discernible performance advantage when using one over the other. The choice between the two can be based on personal preference or specific requirements.
The above is the detailed content of Is There a Performance Difference Between Using `{}` and `make()` to Initialize Maps in Go?. For more information, please follow other related articles on the PHP Chinese website!