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

Barbara Streisand
Release: 2024-10-26 21:28:02
Original
364 people have browsed it

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

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!

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
Latest Articles by Author
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!