as dwn said, performance was one of its advantages when complex processors grew, MSDN blog Non-classic processor behavior: how something can be faster than not doing it gives an example that clearly shows the difference between the ternary (conditional) operator and if / else.
enter the following code:
#include <windows.h> #include <stdlib.h> #include <stdlib.h> #include <stdio.h> int array[10000]; int countthem(int boundary) { int count = 0; for (int i = 0; i < 10000; i++) { if (array[i] < boundary) count++; } return count; } int __cdecl wmain(int, wchar_t **) { for (int i = 0; i < 10000; i++) array[i] = rand() % 10; for (int boundary = 0; boundary <= 10; boundary++) { LARGE_INTEGER liStart, liEnd; QueryPerformanceCounter(&liStart); int count = 0; for (int iterations = 0; iterations < 100; iterations++) { count += countthem(boundary); } QueryPerformanceCounter(&liEnd); printf("count=%7d, time = %I64d\n", count, liEnd.QuadPart - liStart.QuadPart); } return 0; }
the cost for different borders is very different and more strange (see source material). and if you change:
if (array[i] < boundary) count++;
to
count += (array[i] < boundary) ? 1 : 0;
The execution time is now independent of the limit value, since:
the optimizer was able to remove the branch from the ternary expression.
but on my Intel i5 cpu / windows 10 / vs2015 desktop, my test result is very different from the msdn blog.
when using debug mode if / else cost:
count= 0, time = 6434 count= 100000, time = 7652 count= 200800, time = 10124 count= 300200, time = 12820 count= 403100, time = 15566 count= 497400, time = 16911 count= 602900, time = 15999 count= 700700, time = 12997 count= 797500, time = 11465 count= 902500, time = 7619 count=1000000, time = 6429
and the cost of a triple operator:
count= 0, time = 7045 count= 100000, time = 10194 count= 200800, time = 12080 count= 300200, time = 15007 count= 403100, time = 18519 count= 497400, time = 20957 count= 602900, time = 17851 count= 700700, time = 14593 count= 797500, time = 12390 count= 902500, time = 9283 count=1000000, time = 7020
when using release mode if / else cost:
count= 0, time = 7 count= 100000, time = 9 count= 200800, time = 9 count= 300200, time = 9 count= 403100, time = 9 count= 497400, time = 8 count= 602900, time = 7 count= 700700, time = 7 count= 797500, time = 10 count= 902500, time = 7 count=1000000, time = 7
and the cost of a triple operator:
count= 0, time = 16 count= 100000, time = 17 count= 200800, time = 18 count= 300200, time = 16 count= 403100, time = 22 count= 497400, time = 16 count= 602900, time = 16 count= 700700, time = 15 count= 797500, time = 15 count= 902500, time = 16 count=1000000, time = 16
the ternary operator is slower than the if else statement on my machine!
therefore, according to various compiler optimization methods, the ternal and if / else operator can behave very strongly.