Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speed difference between If-Else and Ternary operator in C...?

So at the suggestion of a colleague, I just tested the speed difference between the ternary operator and the equivalent If-Else block... and it seems that the ternary operator yields code that is between 1x and 2x faster than If-Else. My code is:

  gettimeofday(&tv3, 0);
  for(i = 0; i < N; i++)
  {
     a = i & 1;
     if(a) a = b; else a = c;
  }
  gettimeofday(&tv4, 0);


  gettimeofday(&tv1, 0);
  for(i = 0; i < N; i++)
  {
     a = i & 1;
     a = a ? b : c;
  }
  gettimeofday(&tv2, 0);

(Sorry for using gettimeofday and not clock_gettime... I will endeavor to better myself.)

I tried changing the order in which I timed the blocks, but the results seem to persist. What gives? Also, the If-Else shows much more variability in terms of execution speed. Should I be examining the assembly that gcc generates?

By the way, this is all at optimization level zero (-O0).

Am I imagining this, or is there something I'm not taking into account, or is this a machine-dependent thing, or what? Any help is appreciated.

like image 392
Patrick87 Avatar asked Jul 19 '11 21:07

Patrick87


People also ask

Which is faster ternary operator or if-else?

A ternary operator is a single statement, while an if-else is a block of code. A ternary operator is faster than an if-else block.

Is ternary operator faster than if in C?

It is not faster.

Is ternary slower than if-else?

The compiler might as well expand out the ternary into an if-else. Note that x86 is only slower when using ternary -- it is as equally fast as x64 when using if/else.

What is the difference between if if-else ternary operator?

The ternary operator takes 3 different arguments which include the condition, the expression if the condition is true, and the expression if the condition is false. This is extremely similar to how an if / else statement works but the syntax for the ternary operator is much more compact.


2 Answers

You could also go completely branchless and measure if it makes any difference:

int m = -(i & 1);
a = (b & m) | (c & ~m);

On today's architectures, this style of programming has grown a bit out of fashion.

like image 185
fredoverflow Avatar answered Oct 05 '22 23:10

fredoverflow


There's a good chance that the ternary operator gets compiled into a cmov while the if/else results in a cmp+jmp. Just take a look at the assembly (using -S) to be sure. With optimizations enabled, it won't matter any more anyway, as any good compiler should produce the same code in both cases.

like image 39
Anteru Avatar answered Oct 05 '22 23:10

Anteru