通过值或引用传递标量类型:有什么关系?

通过值或引用传递标量类型:有什么关系?

问题描述:

我承认,对于几乎每个人(包括我),微优化是愚蠢,并很可能在所有曾经用C ++编写的程序错误的最大单一原因。但有一些可能被视为良好做法,而且是如此简单易用的..好了,我只是好奇这一点。

I acknowledge that for almost everyone (including me), micro-optimization is stupid and is very probably the largest single cause of mistakes in all of the programs ever written in C++. But some might be considered as "good practices", and are so simple to use that .. well, I'm just curious about this one.

我见过很多人做这样的事情:

I've seen lots of people doing things like:

void function( double x ) {}

和其他人这样做,而不是:

and others doing this instead:

void function( const double& x ) {}

,因为它是所谓的更有效率。说函数被称为可笑经常在程序中,数百万次;我个人相信,这不会在性能方面都重要..但我不肯定知道,不是吗?

because it was supposedly "more efficient". Say that function is called ridiculously often in a program, millions of times; I am personally convinced that this doesn't matter at all in terms of performances.. but I don't know for sure, does it?

如果是这样,为什么/如何?
是否值得 - 考虑到小的努力,这是 - ?以供参考,而不是按值传递标量类型的习惯

If it does, why/how? Is it worth -- considering the small effort that it is -- taking the habit of passing scalar types by reference instead of by value?

长话短说没有,何标,甚至浮点类型都通过寄存器传递特别不是最现代的平台。拇指我见过不停地谈论的一般规则是128字节,当您应该只是按值传递和引用传递的分界线。

Long story short no, and particularly not on most modern platforms where scalar and even floating point types are passed via register. The general rule of thumb I've seen bandied about is 128bytes as the dividing line between when you should just pass by value and pass by reference.

鉴于该数据已经存储在注册你实际速度变慢通过要求处理器出去缓存/内存获取数据的事实。这可能取决于该高速缓存行的数据是无效是一个巨大的打击。

Given the fact that the data is already stored in a register you're actually slowing things down by requiring the processor to go out to cache/memory to get the data. That could be a huge hit depending on if the cache line the data is in is invalid.

在这一天结束,这实际上取决于什么平台ABI和调用约定。大多数现代编译器甚至会使用寄存器传递的数据结构,如果他们将适合(例如两个短裤等的结构)时优化来了。

At the end of the day it really depends on what the platform ABI and calling convention is. Most modern compilers will even use registers to pass data structures if they will fit (e.g. a struct of two shorts etc.) when optimization is turned up.