C++ function parameters: use a reference or a pointer (and then dereference)?

I was given some code in which some of the parameters are pointers, and then the pointers are dereferenced to provide values. I was concerned that the pointer dereferencing would cost cycles, but after looking at a previous StackOverflow article: How expensive is it to dereference a pointer?, perhaps it doesn't matter.

Here are some examples:


bool MyFunc1(int * val1, int * val2)
{
    *val1 = 5;
    *val2 = 10;
    return true;
}

bool MyFunc2(int &val1, int &val2)
{
    val1 = 5;
    val2 = 10;
    return true;
}

I personally prefer the pass-by-reference as a matter of style, but is one version better (in terms of process cycles) than another?


我的经验法则是如果参数可以是NULL,也就是在上述情况下是可选的,并且如果参数不应该为NULL,则通过指针传递。


From a performance point of view, it probably doesn't matter. Others have already answered that.

Having said that, I have yet not found a situation where an added instruction in this case would make a noticeable difference. I do realize that for a function that is called billions of times, it could make a difference. As a rule, you shouldn't adapt your programming style for these kind of "optimizations".


You can get the assembly code from your compiler and compare them. At least in GCC, they produce identical code.

链接地址: http://www.djcxy.com/p/20726.html

上一篇: C ++:按值传递对象的原因

下一篇: C ++函数参数:使用引用还是指针(然后解引用)?