Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Branch on ?: operator?

For a typical modern compiler on modern hardware, will the ? : operator result in a branch that affects the instruction pipeline?

In other words which is faster, calling both cases to avoid a possible branch:

bool testVar = someValue(); // Used later.
purge(white);
purge(black);

or picking the one actually needed to be purged and only doing it with an operator ?::

bool testVar = someValue();
purge(testVar ? white : black);

I realize you have no idea how long purge() will take, but I'm just asking a general question here about whether I would ever want to call purge() twice to avoid a possible branch in the code.

I realize this is a very tiny optimization and may make no real difference, but would still like to know. I expect the ?: does not result in branching, but want to make sure my understanding is correct.

like image 819
WilliamKF Avatar asked Aug 19 '11 21:08

WilliamKF


People also ask

Which is called ternary operator ?: && ===?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

How do I branch in Airflow?

One of this simplest ways to implement branching in Airflow is to use the BranchPythonOperator. Like the PythonOperator , the BranchPythonOperator takes a Python function as an input. However, the BranchPythonOperator's input function must return a list of task IDs that the DAG should proceed with based on some logic.

Is ternary operator a branch?

But the ternary operator (?:) is a branching instruction.

What is in conditional operator?

The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows: The first operand is implicitly converted to bool . It is evaluated and all side effects are completed before continuing.


1 Answers

Depends on the platform. Specifically, it depends on the size of jump prediction table of the CPU and whether the CPU allows conditional operations (like on ARM).

CPUs with conditional operations will strongly favor the second case. CPUs with bigger jump prediction tables will favor the first case.

The real answer (like with any other performance questions): measure and compare. Sometimes the rest of the code throws a curve ball and it's usually impossible to predict effects of some changes.

like image 90
Rom Avatar answered Sep 30 '22 01:09

Rom