In my C++ code, I have to select between two functions that take the same arguments based on a given condition. I could write:
if (condition)
return foo(a, b, c);
else
return bar(a, b, c);
Or:
return (condition? foo : bar)(a, b, c);
But which of these two ways is faster?
EDIT:
I tried to test using this code:
#include <cmath>
#include <chrono>
#include <iostream>
using namespace std;
void foo(float x, float y, int param)
{
pow(x+y, param);
}
void bar(float x, float y, int param)
{
pow(x+y, param);
}
int main() {
const int loops = 1000;
auto t1 = chrono::high_resolution_clock::now();
for(int i = 0; i < loops; i++)
for(int j = 0; j < loops; j++)
(i==j? foo : bar)(i, j, 2);
auto t2 = chrono::high_resolution_clock::now();
for(int i = 0; i < loops; i++)
for(int j = 0; j < loops; j++)
if(i==j)
foo(i, j, 2);
else
bar(i, j, 2);
auto t3 = chrono::high_resolution_clock::now();
cout << "ternary: " << (chrono::duration_cast<chrono::microseconds>(t2-t1).count()) << "us" << endl;
cout << "if-else: " << (chrono::duration_cast<chrono::microseconds>(t3-t2).count()) << "us" << endl;
return 0;
}
With the updated test code I got:
ternary: 70951us
if-else: 67962us