Reputation: 2612
Is it generally better/faster to do:
if (condition) return a
else if (condition2) return b
else return c
or
if (condition) return a
if (condition2) return b
return c
They both do the same thing but I am curious if there are other ramifications that need to be kept in mind when comparing these two snippets
Upvotes: 0
Views: 408
Reputation: 16259
Go with what is most readable and maintainable. You likely won't see any difference between the two versions of code because compilers are usually good at making these sorts of branch optimizations for you. So the resulting compiled code may be essentially the same in both cases. Leave it for the compiler to do this sort of micro optimization.
Upvotes: 1
Reputation: 6036
There is no difference in this case but following examples are different:
if (condition) do work1
else if (cond2) do work2
else if (cond3) do work3
else do work4
more work
If first condition is true then program will move to "more work" statement and no other conditions are tested, but in following all conditions will be tested even if first condition is true (except else):
if (condition) do work1
if (cond2) do work2
if (cond3) do work3
else work4
more work
Thats the only difference and it does not affect speed much unless there are thousands of if statements.
Both have different use cases:
Run first one where you want to stop as soon as a true condition is encountered.
Run second one when you want to test more conditions even after you have found
a true condition.
Upvotes: 0
Reputation: 23
What ELSE IF means is if the previous IF statement isn’t true, then try 'this' one. From my experience, IF works much faster and is great if you only need to check for one condition. ELSE IF is more ideal for different conditions.
Upvotes: -1
Reputation: 753
Since there is always the same amount of code executed, it won't make any difference. In terms of readability of the code I strongly suggest to use the "else" version. In this version you directly see (because of the "else") that the first condition is not true in order to execute the else if branch. In the second example you could miss the "return" when reading and be confused why the code checks for several conditions.
Upvotes: 3
Reputation: 25056
The difference is negligible/none.
When performance-tuning your code, I'd look elsewhere to be honest.
Upvotes: 1
Reputation: 2688
Honestly, I tried testing, and found no difference what-so-ever.
I think it's personal preference over anything else, that and the 2nd one is less code to write...
Upvotes: 0