"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Efficiently Initialize Arrays in Go, Similar to C++'s memset?

How Can I Efficiently Initialize Arrays in Go, Similar to C++'s memset?

Posted on 2025-02-06
Browse:912

How Can I Efficiently Initialize Arrays in Go, Similar to C  's memset?

Is there an Equivalent of memset in Go?

In C , the memset function allows for the efficient initialization of arrays with specific values. In Go, while there is no direct equivalent, several techniques can achieve similar results.

Loop Iteration

The simplest approach is to use a loop to set each element of an array to the desired value.

func memsetLoop(a []int, v int) {
    for i := range a {
        a[i] = v
    }
}

Repeated copy()

Taking advantage of the highly optimized copy() function, we can leverage a repeated copy pattern to efficiently set array values.

func memsetRepeat(a []int, v int) {
    if len(a) == 0 {
        return
    }
    a[0] = v
    for bp := 1; bp 

Benchmark Results

To assess the performance of these techniques, we benchmark them against each other for different array sizes.

var a = make([]int, 1000) // Size will vary

func BenchmarkLoop(b *testing.B) {
    for i := 0; i 

The results show that memsetRepeat() outperforms memsetLoop() for larger arrays, demonstrating its efficiency for fast initialization.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3