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.
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 Module
294.88 ns Access length in For-statement (Faster)
297.07 ns Use local variable for length