LoginSignup
4
1

More than 5 years have passed since last update.

Golangの append と copy はどっちが速いのか

Last updated at Posted at 2017-08-30

Golang のスライスは、append と copy を使って内容を移すことができます。
果たしてどちらが速いのか?

環境

OS: macOS 10.12.6
Go version: 1.8.3

ベンチコード

main_test.go
package main

import "testing"

func BenchmarkAppend(b *testing.B) {
    size := 1000
    src := make([]int, size)
    dst := make([]int, 0, size)
    for i := 0; i < size; i++ {
        src[i] = i
    }
    for i := 0; i < b.N; i++ {
        _ = append(dst, src...)
    }
}

func BenchmarkCopy(b *testing.B) {
    size := 1000
    src := make([]int, size)
    dst := make([]int, size)
    for i := 0; i < size; i++ {
        src[i] = i
    }
    for i := 0; i < b.N; i++ {
        copy(dst, src)
    }
}

ベンチ結果

$ go test -bench=. -benchmem
BenchmarkAppend-4       20000000                98.8 ns/op             0 B/op          0 allocs/op
BenchmarkCopy-4         20000000                97.1 ns/op             0 B/op          0 allocs/op
PASS
ok      github.com/kawasin73/sample/sample13    4.159s
$ go test -bench=. -benchmem
BenchmarkAppend-4       20000000                97.6 ns/op             0 B/op          0 allocs/op
BenchmarkCopy-4         20000000                97.0 ns/op             0 B/op          0 allocs/op
PASS
ok      github.com/kawasin73/sample/sample13    4.123s
$ go test -bench=. -benchmem
BenchmarkAppend-4       20000000                98.2 ns/op             0 B/op          0 allocs/op
BenchmarkCopy-4         20000000                98.6 ns/op             0 B/op          0 allocs/op
PASS
ok      github.com/kawasin73/sample/sample13    4.176s

結論

cap が同じ場合には速度は変わらない。

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1