Home > Backend Development > Golang > Go's Memset Equivalent: How to Efficiently Initialize Arrays with Non-Zero Values?

Go's Memset Equivalent: How to Efficiently Initialize Arrays with Non-Zero Values?

Barbara Streisand
Release: 2025-01-04 02:29:40
Original
857 people have browsed it

Go's Memset Equivalent: How to Efficiently Initialize Arrays with Non-Zero Values?

Go Analog for Memset

Question:

Go programmers seek an efficient method analogous to C 's memset to initialize arrays with non-zero values, as basic loops can be slow.

Answer:

While Go lacks an explicit memset function, there are optimized approaches that emulate its functionality.

Loop-Based Solution:

The simplest alternative is a loop that iterates through the array, assigning the desired value to each element:

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

Copy-Based Solution:

Go's optimized copy() function can be leveraged to initialize arrays quickly. By setting the first element manually and repeatedly copying the filled portion, the number of iterations is reduced to log(n):

func memsetRepeat(a []int, v int) {
    if len(a) == 0 {
        return
    }
    a[0] = v
    for bp := 1; bp < len(a); bp *= 2 {
        copy(a[bp:], a[:bp])
    }
}
Copy after login

Performance Comparison:

For small arrays, the loop-based solution is marginally faster. However, as the array size grows, the copy-based solution becomes significantly faster due to its reduced number of iterations.

Benchmark Results:

Array Size Loop-Based Copy-Based
100 elements 1.15x slower
1,000 elements 2.5x slower
10,000 elements 2x slower
100,000 elements 1.5x slower

The above is the detailed content of Go's Memset Equivalent: How to Efficiently Initialize Arrays with Non-Zero Values?. For more information, please follow other related articles on the PHP Chinese website!

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