Is Slice Assignment Always Faster Than Slice Append in Go?

Linda Hamilton
Release: 2024-11-12 10:19:02
Original
896 people have browsed it

Is Slice Assignment Always Faster Than Slice Append in Go?

Performance Comparison: Slice Append vs Assign in Go

When working with slices in Go, operations such as appending and assigning elements can have significant performance implications. Two common methods for slice append are available:

append(slice, value): This function creates a new slice with an extended capacity to accommodate the new element and copies the existing elements to the new slice.

slice[index] = value: This assignment directly modifies the element at the specified index of the slice without creating a new copy.

To compare the performance of these two approaches, the following two benchmark functions were created:

func BenchmarkSliceAppend(b *testing.B) {
    a := make([]int, 0, b.N)
    for i := 0; i < b.N; i++ {
        a = append(a, i)
    }
}

func BenchmarkSliceSet(b *testing.B) {
    a := make([]int, b.N)
    for i := 0; i < b.N; i++ {
        a[i] = i
    }
}
Copy after login

The results show that slice[index] = value is significantly faster than append(slice, value):

BenchmarkSliceAppend-4  200000000                7.87 ns/op            8 B/op          0 allocs/op
BenchmarkSliceSet-4     300000000                5.76 ns/op            8 B/op
Copy after login

Understanding the Performance Difference

Why is slice assignment faster than slice append? The key difference lies in the fact that assignment is a simple in-place operation that modifies the existing slice without requiring any copies or reallocation.

On the other hand, the append function involves several steps:

  1. Copying the existing slice header
  2. Creating a temporary slice for the variadic parameter
  3. Reslicing the existing slice if necessary
  4. Assigning the new value to an element of the slice
  5. Returning a new slice, which is then assigned to the local variable

Even if some of these steps are optimized or inlined, the need to update the local slice variable in each loop iteration adds computational overhead compared to the simpler assignment operation.

The above is the detailed content of Is Slice Assignment Always Faster Than Slice Append in Go?. 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