Home > Software engineering >  Does anyone know One more if in front of it will not be faster than the next if?
Does anyone know One more if in front of it will not be faster than the next if?

Time:12-03

For example:

1.

if a==1
  process for a
if b==1
  process for a
if a == 1; process for a
else if b === 1; process for b

Which one will be faster ?

CodePudding user response:

They aren't equivalent. If the code is wrong, it doesn't matter how fast it is.

In the first example, both processes a and b (assuming a typo in your code) may run, depending on the values of a and b.

In the second example, at most one process may run, even when a and b are both 1.

To answer the question more generally, stipulating that each test takes the same time to execute, a series of operations guarded by if statements will be slower, since all of the tests will be evaluated (and, consequently, all of the guarded operations may be executed). A series of if-else-if tests will stop executing once a test is found to be true (and only one guarded operation may be executed). So, if-else-if will always be at least as fast as an equivalent series of if, and is likely to be faster, depending on which conditions are true.

CodePudding user response:

In 2, you are definitely saving some condition checking computations since in case of first if being true, program doesn't need to check any upcoming else if conditions.

However, the improvement in speed will be negligible and unnoticeable considering your computer is doing billions of computations per seconds. So saving of few computations are nothing in comparison to what the machine is doing per seconds.

It's like taking few drops from ocean and expect them to make any difference.

That being said, This can be a ton of help when debugging the code later because now you know out of the ifs, if one is executed, flow cannot go into any other ifs present. This saves time and makes the debugging faster.

  • Related