doujiao1948 2016-01-09 22:42
浏览 52
已采纳

指针与值的论点和接收者的权衡

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条回答 默认 最新

  • dtvhqlc57127 2016-01-09 22:50
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失