Jump to content

Is it worse when you use a bunch of If's rather than using ElseIf's?


Recommended Posts

In my program i have a lot of conditions and therefore use a lot of If statements. I sorta have a habit of enjoying the way a short if statement can be, like this:

If $i = 1 Then $text = "hello"

If $i = 2 Then $text = "bye"

And I was wondering if having a lot of those.. would be worse than something like:

If $i = 1 Then

$text = "hello"

ElseIf $i = 2 Then

$text = "bye"

EndIf

I was wondering which is a better programming habit, and why? Or does it not even effect the program at all?

Link to comment
Share on other sites

The second way is better. It is more efficient to use ElseIf, Select Case, and Switches than you use a bunch of If statements. The reason for this is program speed and efficiency. The computer will stop processing the statement as soon as it finds that an ElseIf statement is true. It will then process that and then jump to the next line that follows the Endif without even looking at the Elseif statements that follow the first one that is true. The same is true for Select Case and Switches.

In addition, you generally want to program If Elseif, Select Case, and Switch statements so that the most common result is the first possible match. This prevents the computer from having to do unnecessary logic computations until it reaches the very end of the statement where it finds it to be true.

I hope this answered your question.

"So man has sown the wind and reaped the world. Perhaps in the next few hours there will no remembrance of the past and no hope for the future that might have been." & _"All the works of man will be consumed in the great fire after which he was created." & _"And if there is a future for man, insensitive as he is, proud and defiant in his pursuit of power, let him resolve to live it lovingly, for he knows well how to do so." & _"Then he may say once more, 'Truly the light is sweet, and what a pleasant thing it is for the eyes to see the sun.'" - The Day the Earth Caught Fire

Link to comment
Share on other sites

And to make sure you should do some profiling of some test code.

When I did some time ago I found Select Case and Switch to be a whole lot slower than If..ElseIf.

This could have changed by now as the dev's seems to be optimizing the engine code when they encounter interesting areas or known bottle necks.

Apart from that If...ElseIf should be faster as @The_Kandie_Man pointed out.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...