VB.NET String Length Example

Use the Length property on a String. Describe the performance of accessing Length.
String Length. How many characters are contained in your VB.NET String? With the Length property on the String type, you can determine this count fast.
Length is useful in many VB.NET programs. Its implementation is also interesting to examine. We explore the performance accessing Length in a for-loop.Loop Over String
This program shows the Length property in action. The length of the String "dotnet" is found to be 6 characters. After another 5 characters are appended, the length is now 11 characters.

Immutable: A String cannot be directly changed. So when "perls" is appended to the String, a whole new String is created.


And: During String creation, the length value is stored. The String will thus always have the same length.

VB.NET program that uses Length property Module Module1 Sub Main() ' Get length of string. Dim value As String = "dotnet" Dim length As Integer = value.Length Console.WriteLine("{0}={1}", value, length) ' Append a string. ' ... Then get the length of the newly-created string. value += "perls" length = value.Length Console.WriteLine("{0}={1}", value, length) End Sub End Module Output dotnet=6 dotnetperls=11
Performance. A String's length could be computed once and stored as a field. Or it could be calculated in a loop every time the property is accessed.Property

Important: In VB.NET, the value is stored, which makes getting the length of any string equally fast.

However: If the Length were to be computed each time, a loop over every character that tested against the bound Length would be slow.

And: The developer would have to cache the value. This code is not necessary in VB.NET.

Performance, for-loop. It is typically faster to use Length directly in the bounds of a for-loop. The JIT compiler can make optimizations to help char access.

Note: We run a benchmark that tests Length access in a for-loop. Using a "length" local does not help performance.

A summary. The Length is computed whenever a String is created. When you access Length, characters are not counted: instead the cached value is returned.
We examined Length from a conceptual perspective. Dynamically computing the Length could cause a performance nightmare. But this is not a problem in VB.NET.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to