首頁 > 後端開發 > Golang > Golang 中切片追加和直接賦值哪個比較快?

Golang 中切片追加和直接賦值哪個比較快?

Susan Sarandon
發布: 2024-11-15 02:34:02
原創
622 人瀏覽過

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.

以上是Golang 中切片追加和直接賦值哪個比較快?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板