Skip to content

Instantly share code, notes, and snippets.

@totoleo
Created August 5, 2020 03:50
Show Gist options
  • Save totoleo/b9747686705d8317c336cad871ce1b83 to your computer and use it in GitHub Desktop.
Save totoleo/b9747686705d8317c336cad871ce1b83 to your computer and use it in GitHub Desktop.
slice 复制
package utils
import "testing"
// BenchmarkSliceCopy 对比 slice 通过 loop 和 copy 进行复制的性能
func BenchmarkSliceCopy(b *testing.B) {
const length = 256
type foo struct {
val int
}
var (
int64Src = make([]int64, length)
int64Src2 = make([]int64, length)
float64Src = make([]float64, length)
float64Src2 = make([]float64, length)
structSrc = make([]*foo, length)
byteSrc = make([][]byte, length)
int64Dst = make([]int64, length)
int64Dst2 = make([]int64, length)
float64Dst = make([]float64, length)
float64Dst2 = make([]float64, length)
structDst = make([]*foo, length)
byteDst = make([][]byte, length)
)
for i := 0; i < length; i++ {
int64Src[i] = int64(i)
int64Src2[i] = int64(i)
float64Src[i] = float64(i)
float64Src2[i] = float64(i)
structSrc[i] = &foo{val: i}
byteSrc[i] = []byte{byte(i), byte(i + 1)}
}
b.Run("copy", func(b *testing.B) {
for i := 0; i < b.N; i++ {
copy(int64Dst, int64Src)
copy(int64Dst2, int64Src2)
copy(float64Dst, float64Src)
copy(float64Dst2, float64Src2)
copy(structDst, structSrc)
copy(byteDst, byteSrc)
}
})
b.Run("loop", func(b *testing.B) {
for i := 0; i < b.N; i++ {
byteDstLen := len(byteDst)
structDstLen := len(structDst)
for i := 0; i < len(int64Src); i++ {
int64Dst[i] = int64Src[i]
int64Dst2[i] = int64Src2[i]
float64Dst[i] = float64Src[i]
float64Dst2[i] = float64Src2[i]
if structDstLen > i {
structDst[i] = structSrc[i]
}
if byteDstLen > i {
byteDst[i] = byteSrc[i]
}
}
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment