Knowledge Base, they said. Bah! It's just a hole where we dump all ideas in and bury them!

Monday, October 03, 2005

Evaluate only when necessary

IIf is bad.

This function is a legacy from pre-dotNET Visual Basic to provide a shortcut for evaluating two expressions and returning a result. In the current Visual Basic incarnation, this functionality is still supported mainly for backward compatibility and is located in Microsoft.VisualBasic namespace.

It has been recommended by Microsofties not to use Microsoft.VisualBasic if possible as it will degrade performance by as much as 1000 times.

Unfortunately, only the first paragraph is true. The other two paragraphs are debatable. I use to think that Microsoft.VisualBasic is bad and will degrade performance. I remember reading it somewhere in some article on optimization. However when I went in search of such a thing to link from here, I discovered something new. Apparently, Microsoft.VisualBasic classes and methods are written entirely in dotNET and they are NOT performance degrading. What we are recommended NOT to use is Microsoft.VisualBasic.Compatibility.dll. How embarassing for me.

"The functions in the Microsoft.VisualBasic namespace are built directly on top of the System namespace and provide functionality that goes above and beyond the functionality that the System namespace provides."
~ Panopticon Central

"... the Microsoft.VisualBasic namespace is *NOT* the same thing as the Microsoft.VisualBasic.Compatability namespace."
~ AddressOf.com

Coming back to IIf(), it is still bad because in cases where we use objects with a possibility of containing null value, it will raise a NullReferenceException e.g.

Dim objIifReturn As Object = IIf(Not someObject Is Nothing, someObject.Value, Nothing)

From first look, it would appear that objIifReturn will contain someObject.Value if someObject is not null. However what happens is the dotNET runtime will evaluate someObject AND someObject.Value first. So let's say someObject is null, therefore when the runtime tries to evaluate someObject.Value, it will throw NullReferenceException instead of returning Nothing.

0 Comments:

Post a Comment

<< Home