Link to home
Start Free TrialLog in
Avatar of ysk9818
ysk9818

asked on

What is the Different if the IF..END IF statement is coded Like...

Whatis the different between the following code in term of performance Gain?


If X = Y Then Msgbox "X=Y" Else Msgbox "X<>Y"

IF X=Y Then
   Msgbox "X=Y"
Else
    Msgbox "X<>Y"
End if

Thank

ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yes..readability.

Furthermore, you could replace this:

if a=1 then
  msgbox "test1"
  a=0
  b=3.14
else
  msgbox "test2"
  a=a-1
  b=1.2345
end if

with this:

if a=1 then msgbox "test1":a=0:b=3.14 else msgbox "test2":a=a-1:b=1.2345

and it becomes even MORE unreadable.

The one-line IF structure is really there more for backward compatibilty to when program space was precious, and extra lines of code meant less space for your program.

Do yourself and future maintenance programmers a favor and ALWAYS use the multi-line IF, even if it seems like it could fit on one line like this:
  if bDone then Exit for
Instead do this:

  if bDone then
    Exit For
  End if


only one statement can be executed in the IF or ELSE part by using the first syntax. The second syntax allows you to execute more statements.
>only one statement can be executed

Well, sort of true.  My example above will work even though multiple statements are included.  The key is to separate them with colons (:), but again, this is for backward compatibility and is certainly much less readable than my second version of the same code.

To verify this, create a form with a textbox and command button then add this code:

Private Sub Command1_Click()
  Dim b As single
  Dim a As Integer
  b = 0
  a = Text1.Text
  If a = 1 Then MsgBox "test1": a = 0: b = 3.14 Else MsgBox "test2": a = a - 1: b = 1.2345
  Debug.Print a, b
End Sub

Depending on the value in the textbox, either all of the THEN statements are executed (and values show in the debug window) or all of the ELSE statements are executed.

--
I recommend that if you find code like the above that you convert it to multiline format.
Avatar of ysk9818
ysk9818

ASKER

Thank for all of your comment, since it is only for readability issue, I am agreering with all of your comments, but i can only give the point to one person, and since angels is the first one responding to me i think it is fair that i will give the credit to angels...thank everybody