Is There a Performance Difference Between Using `{}` and `make()` to Initialize Maps in Go?

DDD
Release: 2024-10-30 05:54:02
Original
554 people have browsed it

  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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!