Atlanta Custom Software Development 

   Search        Code/Page

User Login



Forgot the Password?
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
» Regular Expr Tester
» Free Tools

Write concise code with Boolean expressions

Total Hit ( 2329)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article



When setting a Boolean value based upon the result of an expression, avoid using an unnecessary If/Then/Else structure.

Click here to copy the following block
'Instead of using this lengthy syntax . . .
If SomeVar > SomeOtherVar Then
  BoolVal = True
  BoolVal = False
End If

'Use this one, which is easier to read and executes faster. The
'parenthesis are not necessary, but I use them to enhance
'readability when quickly scanning code.
BoolVal = (SomeVar > SomeOtherVar)

The second method ran anywhere between 50% and 85% of the time required for the first method, depending upon which operations were performed in the expression. The parenthesis that I use make no difference in execution speed.
At times, it isn't obvious that you can use this method to write more concise code. The point is that you should keep in mind that all comparison operators are just diadic operators that can return 0 (False) or -1 (True). So, for example the two following pieces of code are absolutely equivalent, but the second runs slightly faster:

Click here to copy the following block
' the standard way
If SomeVar > SomeOtherVar Then
  x = x + 1
End If

' the more concise way
' notice that we need a minus sign to actually add 1 to x
x = x - (SomeVar > SomeOtherVar)

Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with, SQL Server and other MS technologies. He is, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )

Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.