when I run this code
Enum l
NormalFor
NormalForEach
End Enum
Sub Main()
run(l.NormalFor)
run(l.NormalForEach)
Console.Read()
End Sub
Sub run(ByVal l As l)
Dim one(999999) As Integer
Dim two(999, 999) As Integer
Dim three(99, 99, 99) As Integer
Dim r As Random
Dim sw As Stopwatch
r = New Random(42)
Select Case l
Case Module1.l.NormalFor
sw = Stopwatch.StartNew
For i = 0 To 999999
one(i) = r.Next
Next
sw.Stop()
Case Module1.l.NormalForEach
sw = Stopwatch.StartNew
For Each i In one
i = r.Next
Next
sw.Stop()
End Select
Console.WriteLine("One dimension, Array of " & one.Length.ToString & " items " & sw.ElapsedMilliseconds & "ms (" & l.ToString & ")")
r = New Random(42)
Select Case l
Case Module1.l.NormalFor
sw = Stopwatch.StartNew
For i = 0 To 999
For j = 0 To 999
two(i, j) = r.Next
Next
Next
sw.Stop()
Case Module1.l.NormalForEach
sw = Stopwatch.StartNew
For Each i In two
i = r.Next
Next
sw.Stop()
End Select
Console.WriteLine("Two dimension, Array of " & two.Length.ToString & " items " & sw.ElapsedMilliseconds & "ms (" & l.ToString & ")")
r = New Random(42)
Select Case l
Case Module1.l.NormalFor
sw = Stopwatch.StartNew
For i = 0 To 99
For j = 0 To 99
For k = 0 To 99
three(i, j, k) = r.Next
Next
Next
Next
sw.Stop()
Case Module1.l.NormalForEach
sw = Stopwatch.StartNew
For Each i In three
i = r.Next
Next
sw.Stop()
End Select
Console.WriteLine("Three dimension, Array of " & three.Length.ToString & " items " & sw.ElapsedMilliseconds & "ms (" & l.ToString & ")")
End Sub
I get this result
One dimension, Array of 1000000 items 8ms (NormalFor)
Two dimension, Array of 1000000 items 14ms (NormalFor)
Three dimension, Array of 1000000 items 13ms (NormalFor)
One dimension, Array of 1000000 items 9ms (NormalForEach)
Two dimension, Array of 1000000 items 230ms (NormalForEach)
Three dimension, Array of 1000000 items 241ms (NormalForEach)
Anyone know why it's way slower with a >= 2 dimensional array?