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 programs. Its implementation is also interesting to examine. We explore the performance accessing Length
in a for
-loop.
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.
String
cannot be directly changed. So when "perls" is appended to the String
, a whole new String
is created.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 Moduledotnet=6 dotnetperls=11
For
-loopThe 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 Moduleb i r d
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.
string
equally fast.Length
were to be computed each time, a loop over every character that tested against the bound Length
would be slow.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.