Is there a Go equivalent for the C memset function?
In C , memset allows for the initialization of an array with a specific value. This function is particularly efficient. In Go, initializing an array or slice with all zeros is straightforward using make([]int, 1000000); however, this does not provide the option to initialize with non-zero values.
While a loop can be used for manual initialization, it lacks the efficiency of memset.
memset Analogs in Go:
1. Loop-Based Approach:
func memsetLoop(a []int, v int) { for i := range a { a[i] = v } }
2. copy()-Based Approach (Recommended):
The copy() function is highly optimized and can be utilized for memset-like operations.
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]) } }
This solution sets the first element manually and copies the already set parts to the unset parts using copy(). The algorithm uses a doubling approach to reduce the number of iterations to log(n).
Benchmarking:
Benchmarking memsetRepeat() against memsetLoop() shows a noticeable performance advantage for memsetRepeat() as the number of elements increases, particularly around 3800-4000 elements.
Additional Note:
For small slices, memsetLoop() may perform slightly better. However, memsetRepeat() offers significantly better performance for larger slices.
The above is the detailed content of Is there a fast and efficient Go equivalent to C 's memset?. For more information, please follow other related articles on the PHP Chinese website!