performance optimization using 'if' statement.
Old example
1 2 3 4 5 6
|
bool lightCheck();//this function is very simple and doesn't require many processor time
bool hardCheck();//this function is very difficult, it has loops, recursion, and other resource required operations
if (hardCheck() && lightCheck())
{
//do something if both operations are successes.
}
|
New example
1 2 3 4 5 6
|
bool lightCheck();//this function is very simple and doesn't require many processor time
bool hardCheck();//this function is very difficult, it has loops, recursion, and other resource required operations
if (lightCheck() && hardCheck())
{
//do something if both operations are successes.
}
|
As you can see the both example do the same. But if statement has another order.
According to C++ standard statements in 'if' condition calculates from left to right.
So suppose we have condition when
1 2
|
bool res1 = lightCheck(); //res1 == false
bool res2 = hardCheck(); //res2 == true
|
And in the old example we call hardCheck and then lightCheck.
In new example we call only lightCheck().
If the situation is another
1 2
|
bool res1 = lightCheck(); //res1 == true
bool res2 = hardCheck(); //res2 == false
|
Then hardCheck() will be called in both examples, but lightCheck() will be called only in new example.
But as we now lightCheck() doesn't have overhead, so it's ok.
And the another example, it's the same for performance but for difficulty of reading code is another.
Old
1 2 3 4 5 6 7 8
|
SomeType* ptr = init();
if (ptr)
{
if (ptr->get() == true)
{
//do something
}
}
|
New
1 2 3 4 5 6
|
SomeType* ptr = init();
if (ptr && ptr->get() == true)
{
//do something
}
|