devxlogo

Write concise code with Boolean expressions

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 = TrueElse   BoolVal = FalseEnd 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 wayIf SomeVar > SomeOtherVar Then    x = x + 1End If' the more concise way ' notice that we need a minus sign to actually add 1 to xx = x - (SomeVar > SomeOtherVar)

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist