按值或引用传递标量类型:重要吗? [英] Passing scalar types by value or reference: does it matter?

查看:25
本文介绍了按值或引用传递标量类型:重要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当然,微优化很愚蠢 并且可能是实践中许多错误的原因.尽管如此,我已经看到很多人做了以下事情:

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.

这篇关于按值或引用传递标量类型:重要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆