传递参考到输出位置vs使用返回 [英] Pass reference to output location vs using return

查看:131
本文介绍了传递参考到输出位置vs使用返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当调用一个提供简单数据类型的函数时,如果它填充了一个内存位置(通过指针传递)或者返回了简单数据,那么这样做会更好吗?

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使用返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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