问题描述
当调用一个提供简单数据类型的函数时,如果它填充了一个内存位置(通过指针传递)或者返回了简单数据,那么这样做会更好吗?
Which is better for performance when calling a function that provides a simple datatype -- having it fill in a memory location (passed by pointer) or having it return the simple data?
我过度简化了返回静态值5的示例,但假设确定返回值的查找/功能在现实生活中是动态的...
I've oversimplified the example returning a static value of 5 here, but assume the lookup/functionality that determines the return value would be dynamic in real life...
传统逻辑会告诉我第一种方法更快,因为我们通过引用操作,而不是像第二种方法那样返回一个副本...但是,我想要别人的意见。
Conventional logic would tell me the first approach is quicker since we are operating by reference instead of having to return a copy as in the 2nd approach... But, I'd like others' opinions.
感谢
void func(int * a){
* a = 5;
}
或...
int func(){
return 5;
}
int func() { return 5;}
推荐答案
一般来说,函数(也就是返回一个逻辑值),那么最好使用
int func()
。即使返回值是一个复杂的C ++对象,也有一个常见的优化,名为,可避免不必要的对象复制,这两种形式在运行时性能上大致相等。
In general, if your function acts like a function (that is, returning a single logical value), then it's probably best to use
int func()
. Even if the return value is a complex C++ object, there's a common optimisation called Return Value Optimisation that avoids unnecessary object copying and makes the two forms roughly equivalent in runtime performance.
这篇关于传递参考到输出位置vs使用返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!