Home >Backend Development >Golang >Which is Faster: Slice Append or Direct Assignment in Golang?

Which is Faster: Slice Append or Direct Assignment in Golang?

Susan Sarandon
Susan SarandonOriginal
2024-11-15 02:34:02612browse

Which is Faster: Slice Append or Direct Assignment in Golang?

Performance Comparison of slice append and assign in Golang

In Golang, there are two common ways to append elements to a slice: using the append function or directly assigning values to slice indices. To understand the performance differences between these methods, consider the following code:

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
    }
}

Benchmark results show that a[i] = i significantly outperforms a = append(a, i) in terms of execution time:

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

Reason for Performance Difference

The performance difference stems from the underlying operations performed by each method. a[i] = i simply assigns the value i to the ith element of the slice, which is a straightforward and efficient operation.

In contrast, a = append(a, i) involves a more complex process:

  1. The append() function creates a new slice with a size one greater than the current slice a.
  2. It copies the elements of a into the new slice.
  3. It assigns the value i to the last element of the new slice.
  4. The new slice is returned and assigned to the variable a.

This additional copying and allocation contributes to the performance overhead of the append method, resulting in a slower execution time compared to the direct assignment.

Conclusion

For appending elements to a slice, a[i] = i is a more efficient option than a = append(a, i) due to its simpler and faster operation. Keep this in mind when optimizing code performance for slice manipulation tasks.

The above is the detailed content of Which is Faster: Slice Append or Direct Assignment in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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