英文:
Passing slices instead of pointers
问题
我正在阅读一本书,遇到了关于传递参数的话题。
书中说,将数组的切片传递给函数需要24个字节。并且它指出,最好传递切片,因为底层数组不会被复制。但是,只传递指针不是只需要8个字节吗?
书名:《Go语言实战》
传递切片的开销是否如此之小,以至于传递指针是更好的选择?
英文:
I was reading a book and came across this topic about passing parameters.
The book says passing a slice of an array to a function takes 24 bytes. And it states that it is better to pass the slice, because the underlying array will not be copied. But doesn't passing a pointer only take 8 bytes?
Book: Go in action
Is the overhead so little that passing slices is the way to go? Versus passing the pointers
答案1
得分: 2
复制小于缓存行大小(通常在大多数常见CPU上为128字节)的任何内容基本上需要相同的时间,因此8字节和24字节之间没有真正的区别。通常花费的时间更多是在解引用指针而不是复制这么小的内容。
由于通过指针来操作数组的默认方法是在切片内部,因此使用切片而不是指向数组的指针更符合惯用法。然而,书中的引用是指传递数组值,而不是通过指针传递,这将复制整个数组。
英文:
Copying anything less than a cache line (usually 128 bytes on most common CPUs) basically takes the same amount of time, so there's no real difference between 8 bytes and 24. More time is usually spent dereferencing the pointer than copying anything this small.
Since the default method of manipulating arrays via pointers is within a slice, it's more idiomatic to use a slice rather than a pointer to an array. The quote from the book however is referring to passing an array value, not via a pointer, which will copy the entire array.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论