传递切片而不是指针

huangapple go评论77阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2016年3月9日 02:31:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/35875217.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定