Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using intermediate variables for ternary operator (or similar) for better performance?

Tags:

Assume in C++ (or C, Java, etc.) I have code like this:

int a = f() > g() ? f() : g(); 

which of course assigns a with the greater between return values of f() and g(). Now assuming f() and g() are themselves complex and slow, should I replace this line with something like

int f_value = f(); int g_value = g(); int a = f_value > g_value ? f_value : g_value; 

so neither f() and g() will be called twice, or is the compiler (given sufficient optimization) going to do something like this for me anyway so I don't have to do anything?

This general question of course applies to many similar scenarios as well.

like image 313
Peng Avatar asked Jun 14 '16 07:06

Peng


People also ask

Is a ternary operator more efficient?

Ternary operators can be a more concise way in limited situations (your example is a good one). BUT they can often be abused to make code unreadable (which is a cardinal sin) = do not nest ternary operators!

Why ternary operator is better than if else?

Emphasis: value-selection before/after action needing values. There's a different emphasis: An if / else statement emphasises the branching first and what's to be done is secondary, while a ternary operator emphasises what's to be done over the selection of the values to do it with.

What is the limitation of ternary operator comparing with IF statement?

The Ternary Operator is not suitable for executing a function or several statements. In this case, if else is more appropriate. If condition is preferred in case if program requires executing only on true block. In this case, it is necessary to work around to use Ternary Operator.

Is ternary faster than if else JavaScript?

There is no difference in speed.


1 Answers

Generally, no, the compiler won't do it – it can't, actually. Calling f and g could have side effects, and the result of the second call of either f or g might not be the same as in the first call. Imagine something like this:

int f() {     static int n = 0;     return ++n; } 

But there are exceptions proving the rule:

Actually, a compiler is allowed to perform any optimisation it wants to – as long as the optimised code behaves exactly the same (considering any visible effects) as the completely unoptimised one.

So if the compiler can guarantee that omitting the second function call does not suppress any side effects (and only then!), it actually is allowed to optimise the second call away and most likely will do so, too, at higher optimisation levels.

like image 72
Aconcagua Avatar answered Sep 20 '22 07:09

Aconcagua