使用 (const int &var) 形式参数代替 (const int var) 有什么好处吗?
使用 const int &var 形式参数代替 const int var 有什么好处吗?
我知道大型结构的优势,但对于 POD 来说,指针通常与实际数据大小相同。所以我想答案是“没有优势”。但我认为,按值传递语义可能会复制一次到堆栈,然后再次复制到堆栈外的区域以便于引用(例如寄存器)。或者也许不是。事实上,按值传递可能更好,
http: //www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
因为引用通常由 C++ 使用指针实现,并且取消引用指针比直接访问它慢,所以访问按引用传递的值比访问按值传递的值慢。
但这又回到了我所说的从堆栈中复制回来的问题。我只是偏执吧?这种行为是由编译器而不是我来担心的。
我可以单步执行我所知道的程序集,但是,谷歌搜索速度更快,而且结果是空白的。
Is there anything to be gained by using const int &var
formal parameters in place of const int var
?
I know the advantage in large structs but for PODs the pointer is often of equal size to the actual data. So I guess the answer would be "No advantage". But I think perhaps the pass by value semantics copies once to the stack and again to an area off the stack for easier reference (say to a register). Or maybe not. In fact it may infact be better to pass by value,
http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
Because references are typically implemented by C++ using pointers, and dereferencing a pointer is slower than accessing it directly, accessing values passed by reference is slower than accessing values passed by value.
But this gets back to what I was saying about copying back off the stack. I'm just being paranoid right? This behaviour is for the compiler to worry about and not me.
I could single step the assembly I know, but, well, googling is faster and it came up blank.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
考虑一下:
非引用
引用
使用引用版本稍微慢一些。但一般来说,让编译器担心它。如果它是只读值,只需给它一个常规的旧 int 即可。如果需要修改调用者的值,请使用引用或指针。
当然,这只适用于像 int 这样的小数据类型。如果您正在谈论更大的东西,例如结构或其他东西,那么使用引用可能会更快。
Consider this:
Non-reference
Reference
It's slightly slower to use the reference version. Generally though, let the compiler worry about it. If it's a read-only value, just give it a regular old int. If you need to modify the caller's value, use a reference or a pointer.
Of course that's only true for a small data type like an int. If you were talking about something bigger like a struct or something it would probably be faster to use a reference.
当您传递引用时,您会复制引用的值,一切都是一样的。当您使用它时,您会在间接上浪费一些周期,但除此之外没有任何性能差异。
当然,如果您放弃常量性,或者如果您更改不同线程上的引用值,则程序行为可能会有所不同。
When you pass a reference you copy the value of the reference, all the same. When you use it, you waste a few cycles on indirection, but other than that there is no performance difference.
Of course, there could be a difference in program behaviour, if you cast away constness, or if you change the referenced value on a different thread.