dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: VB4,VB5,VB6,VBS
Expertise: beginner
Oct 16, 1999

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


Write concise code with Boolean expressions

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

'Instead of using this lengthy syntax . . .
If SomeVar > SomeOtherVar Then
   BoolVal = True
Else
   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:


' 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)
Bryan Fazekas
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date