func copy(dst, src []Type) int
如果dst == src,我记得C++中memcpy如果二者相同则不执行拷贝,因为拷不拷贝结果都一样。
golang会这样吗?我用下列代码试了一下,结果不管dst和src是否相同,执行效率都一样,t3-t2和t2-t1基本接近。是不是能说明不管怎样,copy都执行了拷贝?哪位大神能提供一下源码?
func TestSomething() {
a_size := uint32(1024 * 1024)
copy_size := uint32(1024 * 1024)
r := rand.New(rand.NewSource(time.Now().UnixNano()))
a := make([]byte, a_size, a_size)
for i := 0; i < len(a); i += 1 {
a[i] = byte(r.Intn(0xFF) + 1) //随便赋值
}
a_same := a[:copy_size]
a_diff := make([]byte, copy_size, copy_size)
for i := 0; i < len(a_diff); i += 1 {
a_diff[i] = byte(r.Intn(0xFF) + 1) //随便赋值
}
fmt.Printf("a:%p, a_same:%p, a_diff:%p\n", a, a_same, a_diff)
t1 := time.Now().UnixNano()
for i := 1; i < 1000000; i += 1 {
copy(a, a_same) //a和a_same引用同一空间
}
t2 := time.Now().UnixNano()
fmt.Printf("copy same addr, time:%v\n", t2-t1)
for i := 1; i < 1000000; i += 1 {
copy(a, a_diff) //a和a_diff引用不同空间
}
t3 := time.Now().UnixNano()
fmt.Printf("copy diff addr, time:%v\n", t3-t2)
}
有疑问加站长微信联系(非本文作者)
![](https://static.golangjob.cn/static/img/footer.png?imageView2/2/w/280)