按值或引用传递标量类型:重要吗?
当然,微优化很愚蠢 并且可能是实践中许多错误的原因.尽管如此,我已经看到很多人做了以下事情:
Granted, micro-optimization is stupid and probably the cause of many mistakes in practice. Be that as it may, I have seen many people do the following:
void function( const double& x ) {}
代替:
void function( double x ) {}
因为据说它更有效".假设 function
在程序中经常被荒谬地调用数百万次;这种优化"到底重要吗?
because it was supposedly "more efficient". Say that function
is called ridiculously often in a program, millions of times; does this sort of "optimisation" matter at all?
长话短说不,尤其是在大多数现代平台上,标量甚至浮点类型通过寄存器传递.我见过的一般经验法则是 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 和调用约定是什么.大多数现代编译器甚至会使用寄存器来传递数据结构,前提是它们在优化时适合(例如两个 short 的结构等).
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.