Golang slice append vs assign performance

后端 未结 2 942
没有蜡笔的小新
没有蜡笔的小新 2021-01-01 14:47

To make slice append operation faster we need to allocate enough capacity. There\'s two ways to append slice, Here is the code:

func BenchmarkSliceAppend(b *t         


        
2条回答
  •  孤街浪徒
    2021-01-01 15:51

    It seems like some improvements of Go compiler or runtime have been introduced since this question has been posted, so now (Go 1.10.1) there is no significant difference between append and direct assignment by index.

    Also, I had to change your benchmarks slightly because of OOM panics.

    package main
    
    import "testing"
    
    var result []int
    
    const size = 32
    
    const iterations = 100 * 1000 * 1000
    
    func doAssign() {
        data := make([]int, size)
        for i := 0; i < size; i++ {
            data[i] = i
        }
        result = data
    }
    
    func doAppend() {
        data := make([]int, 0, size)
        for i := 0; i < size; i++ {
            data = append(data, i)
        }
        result = data
    }
    
    func BenchmarkAssign(b *testing.B) {
        b.N = iterations
        for i := 0; i < b.N; i++ {
            doAssign()
        }
    }
    
    func BenchmarkAppend(b *testing.B) {
        b.N = iterations
        for i := 0; i < b.N; i++ {
            doAppend()
        }
    }
    

    Results:

    ➜  bench_slice_assign go test -bench=Bench .
    goos: linux
    goarch: amd64
    BenchmarkAssign-4       100000000           80.9 ns/op
    BenchmarkAppend-4       100000000           81.9 ns/op
    PASS
    ok      _/home/isaev/troubles/bench_slice_assign    16.288s
    

提交回复
热议问题