What is the most efficient method for looping through a SortedList in VB 2008?
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
开发者_StackOverflow 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
On my system the "for i = 1 " loop was faster for the first test (the first click of the button of the program run) by about 20 percent. But the "for each" loop was a hair faster on subsequent tests. The "for each" loop took a little more memory, but this is temporary and will be eventually garbage collected.
The pros and cons of "for each" and "for i = " have been debated here. For each is nice because it works with structures other than arrays, and makes an object available. "For i =" has the advantage of designating the bounds and order of array items in the loop, and avoids a bug you can encounter with arrays:
Dim a(50) As Integer
Dim i As Integer
For Each i In a
i = 22
Next i
In this example, the array is never initialized to 22. The variable i is just a copy of an array element, and the original array element is not changed when i is assigned 22.
精彩评论