1
下面的代碼顯示了我(我認爲)「for each」循環比「i to n」循環快10%左右,但「for each」循環在新內存中創建567k?這是正確的嗎?在速度和內存使用方面,哪種方式通常效率最高?在VB 2008中循環SortedList的最有效方法是什麼?
如果你想在VB中運行這個代碼,只需在表單中添加一個按鈕和兩個標籤。
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
可能的重複項:http://stackoverflow.com/questions/472191/c-for-vs- foreach – 2009-10-29 03:21:36
它不是重複的......線程甚至不提及單詞記憶。 – SteveGSD 2009-10-29 13:32:09