Reputation: 31
I have a quick question about optimizing the speed of my code.
Is it faster to return a double in a function or to have a pointer to your double as one of your arguments?
Returning double
double multiply(double x,double y) {
return x * y;
}
Pointer argument
void multiply(double x,double y,double *xy) {
*xy = x * y;
}
Upvotes: 2
Views: 66
Reputation: 372664
The sort of decision you're talking about here is often called a microoptimization - you're optimizing the code by making a tiny change rather than rethinking the overall strategy of the program. Typically, "microoptimization" has the connotation of "rewriting something in a less obvious way with the intent of squeezing out a little bit more performance." The language's explicit way of communicating data out of a function is through return values and programmers are used to seeing that for primitive types, so if you're going to go "off script" and use an outparameter like this, there should be a good reason to do so.
Are you absolutely certain that this code is executed so frequently that it's worth considering a rewrite that makes it harder to read in the interest of efficiency? A good optimizing compiler is likely to inline this function call anyway, so chances are there's not much of a cost at all. To make sure it's worth actually rewriting the code, you should start off by running a profiler and getting hard evidence that this particular code really is a bottleneck.
Once you've gathered evidence that this actually is slowing your program down, take a step and ask - why are you doing so many multiplications? Rather than doing a microoptimization, you might ask whether there's a different algorithm you could use that requires fewer multiplications. Changes like those are more likely to lead to performance increases.
Finally, if you're sure this is the bottleneck, and you're sure that there is no way to get rid of the multiplications, then you should ask whether this change would do anything. And for that, the only real way to find out would be to make the change and measure the difference. This change is so minor that most good compilers would be smart enough to realize what you're doing and optimize accordingly. As a result, I'd be astonished if you actually saw a performance increase here.
To summarize:
Readability is so much more valuable than efficiency that, as a starting point, it's worth using the "right" language feature for the job. Just use a return statement initially.
If you have hard, concrete evidence that the function you have is a bottleneck, see whether you actually need to call the function that many times by looking for bigger-picture ways of optimizing the code.
If you absolutely need to call the function that many times, then make the change and see if it works - but don't expect that it's actually going to make a difference because the change is minor and optimizing compilers are smart.
Upvotes: 4