Len() function vs String.Length property; which to choose?
So according to this:
Len, another classic BASIC function, returns the length of a string. System.String has the Length property that provides the same information. Is one better than the other?
Performance-wise, these two functions show little difference over 1000’s of iterations. There doesn’t appear to be any reason to prefer one over the other in this case plus there is no functional difference. I’m kind of partial to using the property value rather than the VB function since it encourages thinking of .NET strings as objects. However, at the core, it’s really only a personal preference thing.
If you trust their word, then there's your answer. Otherwise, coding up a test and iterating should give you the final answer.
I'm not sure about the specifics of the Len()
method (my language of choice is C#), but I would say definitely go with the Length
property. Length
is a member of the System.String
class, whereas Len()
isn't.
My guess is that Len()
is just a VB shim on top of the Length
property. Someone could probably make the argument that using Len()
is more idiomatic, from a VB point of view. I think I'd prefer to use the property built in to the class, rather than just use a different mechanism just because it's provided by the language.
The Len
method is provided for backwards compatibility with old VB6 (and earlier) non-.NET code. There's nothing technically wrong with using it. It will work, and just as well, at that. But, it's better to use the new .NET way of doing things whenever possible. Outside of getting you more into the ".NET mindset", though, the only real tangible benefit of using String.Length
is that it makes it easier to port the code to other .NET languages in the future.
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.