Question

is there be any performance effect on "Lines of code - (C)" running inside nested ifs?

if (condition_1)
{
   /* Lines of code */ - (A)

   if (condition_2)
   {
      /* Lines of code */ - (B)

      if (condition_n)
      {
          /* Lines of code */ - (C)
      }
   }
}

Does that mean you can nest any number of if statements without effecting the execution time for the code enclosing at the end of last if statement?

Was it helpful?

Solution

Remember C and C++ are translated to their assembly equivalents. In most cases, this is likely to be via some form of compare (e.g. cmp) and some form of jmp instruction.

As such, whatever code is generated from (C) will still be the same. The if nesting has no bearing on the output. If the resultant code is to generate add eax, 1 no matter how many ifs precede that, it will still be the same thing.

The only performance penalty will be in the number of if statements you use and whether or not the resultant assembly (jxx) is expensive on your system. However, I doubt that repeated nested use of if is likely to be a performance bottleneck in your application. Usually, it is time required to process data and or time required to get data.

OTHER TIPS

You won't affect the execution time of the indicated code itself, but if evaluating your conditions is complex, or affected by other factors, then it could potentially lengthen the total time of execution.

The code will run as fast as if it was outside. Just remember that evaluating an expression (in a if statement) is not "free" and will take a bit of time (more if the condition is more complex), so if your code is deeply nested it will take more time to reach it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top