Go 实战之切片深拷贝


结论

可以看到,两者的性能差距还是有的,copy 显然更快一些,但是性能差距不算特别大

使用 copy 的写法和使用 append 的写法进行切片深拷贝的性能对比如下

大量小数据

code

下面的代码,由于是进行测试大内存拷贝,因此复现时请确定是否有足够的空间

package main

import (
	"testing"
)

var src = make([]string, 1e9)

func init() {
	for i := 0; i < 1e9; i++ {
		src[i] = "hello world"
	}
}
func fnCopy(dst, src []string) {
	copy(dst, src)
}

func fnAppend(dst, src []string) {
	dst = append(dst, src[:1e9]...)
}

func BenchmarkFnCopy(b *testing.B) {
	dst := make([]string, 1e9)
	for i := 0; i < b.N; i++ {
		fnCopy(dst, src)
	}
}
func BenchmarkFnAppend(b *testing.B) {
	dst := make([]string, 0, 1e9)
	for i := 0; i < b.N; i++ {
		fnAppend(dst, src)
	}
}

实验结果


goos: windows
goarch: amd64
pkg: learn
cpu: Intel(R) Core(TM) i7-10750H CPU @ 2.60GHz
BenchmarkFnCopy
BenchmarkFnCopy-12      	       1	99112621500 ns/op
BenchmarkFnAppend
BenchmarkFnAppend-12    	       1	149246719800 ns/op
PASS
goos: windows
goarch: amd64
pkg: learn
cpu: Intel(R) Core(TM) i7-10750H CPU @ 2.60GHz
BenchmarkFnCopy
BenchmarkFnCopy-12      	       1	67865371500 ns/op
BenchmarkFnAppend
BenchmarkFnAppend-12    	       1	125572809100 ns/op
PASS
goos: windows
goarch: amd64
pkg: learn
cpu: Intel(R) Core(TM) i7-10750H CPU @ 2.60GHz
BenchmarkFnCopy
BenchmarkFnCopy-12      	       1	92732291200 ns/op
BenchmarkFnAppend
BenchmarkFnAppend-12    	       1	108871418400 ns/op
PASS

少量大数据

Code

package main

import (
	"testing"
)

var src = make([][]byte, 1e2)

func init() {
	for i := 0; i < 1e2; i++ {
		src[i] = make([]byte, 1e8)
	}
}
func fnCopy(dst, src [][]byte) {
	copy(dst, src)
}

func fnAppend(dst, src [][]byte) {
	dst = append(dst, src[:1e2]...)
}

func BenchmarkFnCopy(b *testing.B) {
	dst := make([][]byte, 1e2)
	for i := 0; i < b.N; i++ {
		fnCopy(dst, src)
	}
}
func BenchmarkFnAppend(b *testing.B) {
	dst := make([][]byte, 0, 1e2)
	for i := 0; i < b.N; i++ {
		fnAppend(dst, src)
	}
}

实验结果

goos: windows
goarch: amd64
pkg: learn
cpu: Intel(R) Core(TM) i7-10750H CPU @ 2.60GHz
BenchmarkFnCopy
BenchmarkFnCopy-12      	47998848	        25.95 ns/op
BenchmarkFnAppend
BenchmarkFnAppend-12    	48002496	        25.91 ns/op
PASS
goos: windows
goarch: amd64
pkg: learn
cpu: Intel(R) Core(TM) i7-10750H CPU @ 2.60GHz
BenchmarkFnCopy
BenchmarkFnCopy-12      	49268566	        24.61 ns/op
BenchmarkFnAppend
BenchmarkFnAppend-12    	49341698	        25.11 ns/op
PASS
goos: windows
goarch: amd64
pkg: learn
cpu: Intel(R) Core(TM) i7-10750H CPU @ 2.60GHz
BenchmarkFnCopy
BenchmarkFnCopy-12      	40344405	        25.73 ns/op
BenchmarkFnAppend
BenchmarkFnAppend-12    	50802681	        25.50 ns/op
PASS

大量大数据

由于内存不够大,暂时未能进行测试


如果本文帮助到了你,帮我点个广告可以咩(o′┏▽┓`o)


评论
  目录