英文:
Pointer vs Value arguments and receivers trade-offs
问题
我来自C++世界,熟悉移动语义和RVO(返回值优化)等概念。
因此,我想知道当你通过值传递参数时是否存在任何权衡之处?
在我的情况下,我有一些非常大的结构体需要传递给一系列函数。据我所了解,每次将一个值传递给函数时,都会创建一个副本。相比之下,传递指针而不是值会更好吗?
我认为唯一的权衡是原始对象可能会被意外或无知地更改,并且对于调用者来说,传递的参数是否可以修改不太清楚。
如果传递的值没有被修改,是否存在优化的可能性?
英文:
I've come from C++ world with such things like the move semantic and RVO.
Since that, I wonder are there any trade-offs when you pass arguments by value?
In my case, I have pretty big structs that I need to pass to a bunch of functions. As I have understood, every time I pass a value to a function, a copy will be created. Would it be better to pass pointers instead of values?
I see the only trade-offs that the original object could be changed accidentally or ignorantly, and it is unclear for a caller that a passed argument is not supposed to be modified.
Is there an optimization if a passed value has not been modified?
答案1
得分: 4
这个没有优化,所有的东西都会被复制。关键是被复制的不同字段的数量(例如,如果你有一个成员是一个结构体,那么其中的字段数量也很重要)。
所以,如果你有非常复杂的结构体,并且性能非常关键,以至于这可能成为一个瓶颈,那么即使对于不可变的东西,你也应该使用指针。
我写了一个小的基准测试,调用一个具有15个字段的结构体的方法,一个方法是指针方法,另一个是值方法,结果如下:
BenchmarkValue 100000000 12.1 ns/op
BenchmarkPointer 2000000000 0.42 ns/op
英文:
There's no optimization for this, and everything will get copied around. It comes down to the amount of distinct fields being copied (i.e. if you have a member that is a struct, the number of fields in it matter as well of course).
So if you have very complex structs, and performance is so critical that this might become a bottleneck, then you should use pointers even for immutable stuff.
I've written a little benchmark that calls a method that does nothing on a struct with 15 fields. One method is a pointer and the other is a value method. the result:
BenchmarkValue 100000000 12.1 ns/op
BenchmarkPointer 2000000000 0.42 ns/op
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论