简体   繁体   English

将参数作为值传递为const引用的性能

[英]Performance of passing argument as value vs as const reference

Does it matter whether or not I pass a small object by const value or const reference on a mondern compiler? 是否在mondern编译器上通过const值或const引用传递小对象是否重要? For example I have a couple of methods accepting and not modifying boost::units::quantity<boost::units::si::length, float> which should be optimized to float anyway. 例如,我有两种方法可以接受而不修改boost :: units :: quantity <boost :: units :: si :: length,float> ,这些方法无论如何都要进行浮动优化。

Normally I would declare the argument's type as a const reference but I'm afraid the compiler cannot optimize the templates way if I do that. 通常,我会将参数的类型声明为const引用,但如果这样做,恐怕编译器无法优化模板方式。

Edit: what I didn't think of but was mentioned by rahul.deshmukhpatil in the comments, if I accept const& the compiler has to at least emit double code in the case I'm invoking from a multithreaded enviroment. 编辑:我没有想到,但在评论中被rahul.deshmukhpatil提及,如果我接受const& ,则在从多线程环境中调用的情况下,编译器必须至少发出双倍代码。

If it's a POD, I would expect that passing it by value will result in slightly faster overall performance. 如果是POD,我希望按值传递它会导致整体性能稍快。 By "slightly" I mean "only someone in a certain, specific, line of work where sanity has less priority than every nanosecond of performance, would care". “略”是指“只有在某些特定,特定的工作领域中,只有人们对健康的重视程度低于每纳秒的性能,才会有人关心”。

To understand why, it is necessary to understand how, on traditional hardware, functions calls are made, and arguments get passed. 要了解原因,有必要了解在传统硬件上如何进行函数调用以及传递参数。

Beyond PODs, the only answer would be to try either way, and gather some statistics. 除POD之外,唯一的答案就是尝试其中一种方法,并收集一些统计信息。

And if you really do not care about a few nanoseconds' worth of difference, do what is more convenient for you. 而且,如果您真的不在乎几纳秒的差值,请执行对您而言更方便的事情。

And, in either case, templates are irrelevant. 而且,无论哪种情况,模板都是不相关的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM