Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 585
Alan K Avatar asked Aug 20 '12 04:08

Alan K


People also ask

Is string length a function or a property Python?

Python String Length | len() Method with Example It is an inbuilt function in python that returns the length (number of characters) of string in Python.

Is Len () a function or a method?

The function len() is one of Python's built-in functions. It returns the length of an object. For example, it can return the number of items in a list. You can use the function with many different data types.

Why is len a function not a method in Python?

The fact that len is a function means that classes cannot override this behaviour to avoid the check. As such, len(obj) gives a level of safety that obj. len() cannot.

Which function is used to get the length of a string value?

As you know, the best way to find the length of a string is by using the strlen() function.


1 Answers

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.

like image 154
Mark Hurd Avatar answered Oct 12 '22 13:10

Mark Hurd