String Length ExampleUse the Length property on a String. Describe the performance of accessing Length.
This page was last reviewed on Dec 8, 2022.
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.
Property uses. Length is useful in many programs. Its implementation is also interesting to examine. We explore the performance accessing Length in a for-loop.
Example. We see the Length property inaction. The length of the String "dotnet" is found to be 6 characters. After another 5 characters are appended, the length is now 11 characters.
Detail 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.
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
dotnet=6 dotnetperls=11
For-loop. The Length of a string is often used in a For-loop in VB.NET programs. Each character can be tested or handled, one-by-one.
Module Module1 Sub Main() Dim animal as String = "bird" ' Loop until length minus 1. For i as Integer = 0 To animal.Length - 1 Console.WriteLine(animal(i)) Next End Sub End Module
b i r d
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.
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.
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 is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 8, 2022 (edit link).
© 2007-2024 Sam Allen.