String
For and For-Each
loops pass over Chars in Strings. With these loops we access each individual character. We then can make a decision based on its value.
We demonstrate String
loops in VB.NET. Further, we test the performance of accessing the Length
and storing it in a local variable outside of the loop.
This program declares a String
that contains some characters. Next, the For-Each
loop is used. It declares a variable for the loop (element) and uses the For Each
, As, In syntax.
For
-loop is next—it uses the For, As, To syntax. This is the standard loop syntax in VB.NET.input.Length
-1) has one subtracted from the max. This means the maximum index is one less than the length.For
-loop, we get the Char
with an element indexing expression (input(i)).Module Module1 Sub Main() ' Input string. Dim input As String = "abc" Console.WriteLine("-- For Each --") ' Use For Each loop on string. For Each element As Char In input Console.WriteLine(element) Next Console.WriteLine("-- For --") ' Use For loop on string. For i As Integer = 0 To input.Length - 1 Dim c As Char = input(i) Console.WriteLine(c) Next End Sub End Module-- For Each -- a b c -- For -- a b c
Should we store the length of the string
in local, and access that, for the fastest string
loop? Here we test 2 versions of a method that loops over a string
.
Length
of the string
is accessed directly in the loop bounds (we use a For
-loop here).string
. We then access that in the loop expression.Length
is a local variable in VB.NET.Module Module1 Sub Main() Dim m As Integer = 10000000 Dim s1 As Stopwatch = Stopwatch.StartNew For i As Integer = 0 To m - 1 ' Version 1: do not store length in local variable. A() Next s1.Stop() Dim s2 As Stopwatch = Stopwatch.StartNew For i As Integer = 0 To m - 1 ' Version 2: store length in local. B() Next s2.Stop() Dim u As Integer = 1000000 Console.WriteLine(((s1.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns")) Console.WriteLine(((s2.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns")) End Sub Sub A() Dim value As String = "birds of a feather" Dim sum As Integer = 0 For i As Integer = 0 To value.Length - 1 If value(i) = "a" Then sum += 1 End If Next End Sub Sub B() Dim value As String = "birds of a feather" Dim sum As Integer = 0 Dim lengthCache As Integer = value.Length - 1 For i As Integer = 0 To lengthCache If value(i) = "a" Then sum += 1 End If Next End Sub End Module294.88 ns Access length in For-statement (Faster) 297.07 ns Use local variable for length
Looping over the characters in a String
is common. We can test for invalid characters, search for a certain sequence of characters, or build up a separate data structure.