The code below shows me (I think) that the "for each" loop is about 10% faster than the "i to n" loop, but the "for each" loop creates 567k in new memory? Is this right? Which way is generally most efficient with regards to speed and memory usage?
If you want to run this code in VB just add a button and 2 labels to a form.
Public Class StateObject
Public WorkSocket As String = "FFFFFFFFFFFF"
Public BufferSize As Integer = 32767
Public Buffer(32767) As Byte
End Class
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For cnt As Integer = 1 To 250
Dim StateObjecter As New StateObject
ClientNetList.Add(cnt.ToString, StateObjecter)
Next
End Sub
Private ClientNetList As New SortedList(Of String, StateObject)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim stop1 As New Stopwatch
Dim stop2 As New Stopwatch
Dim TotalMemory1 As Integer = GC.GetTotalMemory(False)
stop1.Start()
For cnt As Integer = 1 To 1000000
For i = 0 To ClientNetList.Count - 1
ClientNetList.Values(i).WorkSocket = "FFF"
Next
Next
stop1.Stop()
Dim TotalMemory2 As Integer = GC.GetTotalMemory(False)
MsgBox(TotalMemory2 - TotalMemory1)
TotalMemory1 = GC.GetTotalMemory(False)
Dim fff As Integer = GC.GetGeneration(ClientNetList)
stop2.Start()
For cnt As Integer = 1 To 1000000
For Each ValueType As StateObject In ClientNetList.Values
ValueType.WorkSocket = "FFF"
Next
Next
stop2.Stop()
Dim ffff As Integer = GC.GetGeneration(ClientNetList)
TotalMemory2 = GC.GetTotalMemory(False)
MsgBox(TotalMemory2 - TotalMemory1)
Label1.Text = "i: " & stop1.ElapsedMilliseconds
Label2.Text = "e: " & stop2.ElapsedMilliseconds
End Sub