If the result might vary during a single run, you may be able to use lazy evaluation of boolean operators to split your condition into a cheap part and an expensive part, and run the cheap part first.
if (a = 5 && somethingexpensive())
{
...
}
Since calculating a = 5
is cheaper than somethingexpensive()
, and if it is almost always false
you should run it first, which avoids evaluating the somethingexpensive
clause.
If on the other hand the result is constant for a run of the program, you can optimise it by storing the result of the calculation in a static or global variable.
static int result = doevalfunctiononlyonce()
if (result)
{
....
}
This way you have reduced the cost of the if
to a simple memory lookup.
If the condition only changes in response to an action in another procedure, you can update the global from that procedure:
int condition;
void appendToList(int a)
{
list.append(a);
if (list.somethingexpensive())
{
condition = true;
} else
{
condition = false;
}
}
void someotherfunction()
{
// if (list.somethingexpensive())
if (condition)
{
...
}
}
This is useful if someotherfunction
is called lots more often than the appendtolist
function.