Len() function vs String.Length property; which to choose?

Alan K picture Alan K · Aug 20, 2012 · Viewed 23.2k times · Source

I'm making the transition from VB6 to VB.Net (VS 2010) and have a basic rather than expansive understanding of the latter. I obviously have quite a bit of code to... I hesitate to use the word "upgrade" when "port" would be more apt given that the upgrade wizard in past versions of VS may as well have just commented out the code and said "Hey, why don't you re-start from scratch?"

In one procedure which I'm bringing across the Len() function was used to determine the length of a string variable. That still works in VB.Net (though I imagine that it's actually a call to the Strings.Len Method), but the other alternative is to just query the .Length property of the variable.

The question is which to use and why. I've looked through the relevant MSDN pages and all they seem to tell me is that the method/property exists. Nothing is said about performance issues, particularly when loops of large numbers of calls might be involved.

My question, then, is whether anyone is aware of any tested and confirmed benefit of using one approach over the other, or whether it's merely a question of personal preference. Any pointers on similar situations that I might encounter as I make the progression would also be appreciated though given the Stack Overflow guidelines it's just this one issue that I'm interested in seeing whether there's a specific answer to.

Answer

Mark Hurd picture Mark Hurd · Aug 20, 2012

Because you're using VB.NET, your Strings can be Nothing and unless you explicitly check for that, most VB methods, including Len, will treat it the same as String.Empty i.e. "".

With Reflector you can see Len is implemented as a null check, returning 0 for Nothing and otherwise returning .Length, and the JITter will likely in-line the call.

So, if you're using other VB methods, I'd suggest using Len too, unless you know the String is not Nothing or check for Nothing everywhere.