Home  >  Article  >  Backend Development  >  Go Map Initialization: Is `make` Faster Than `{}`?

Go Map Initialization: Is `make` Faster Than `{}`?

Barbara Streisand
Barbara StreisandOriginal
2024-10-26 21:28:02355browse

 Go Map Initialization: Is `make` Faster Than `{}`?

Map Initialization in Go: make vs. {}

In Go, maps can be initialized using either the {} literal syntax or the make function. This article compares the performance of these two approaches.

Performance Differences

Benchmark tests suggest that there is negligible performance difference between initializing a map using {} or make. Results may vary slightly depending on the dataset size and machine specifications, but in general, both methods perform equivalently.

Benchmark Code

The following code defines two benchmark functions, BenchmarkMakeLiteral and BenchmarkMakeMake, which compare the performance of initializing a map using the {} literal and make function, respectively:

<code class="go">package main

import "testing"

func BenchmarkMakeLiteral(b *testing.B) {
    var m map[string]int
    for n := 0; n < b.N; n++ {
        m = InitMapLiteral()
    }
}

func BenchmarkMakeMake(b *testing.B) {
    var m map[string]int
    for n := 0; n < b.N; n++ {
        m = InitMapMake()
    }
}

func InitMapLiteral() map[string]int {
    return map[string]int{}
}

func InitMapMake() map[string]int {
    return make(map[string]int)
}</code>

Conclusion

Based on benchmark results, there is no significant performance difference between initializing a map using the {} literal or make function. The choice of initialization method should be based on personal preference or specific requirements of the program.

The above is the detailed content of Go Map Initialization: Is `make` Faster Than `{}`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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