2009-10-29 99 views
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 
+0

可能的重複項:http://stackoverflow.com/questions/472191/c-for-vs- foreach – 2009-10-29 03:21:36

+0

它不是重複的......線程甚至不提及單詞記憶。 – SteveGSD 2009-10-29 13:32:09

回答

1

在我的系統中「對於i = 1」環是由約20%更快用於第一測試(程序運行的按鈕的第一次點擊)。但是在後續的測試中,「for each」循環的髮型更快。 「爲每個」循環需要更多的內存,但這是暫時的,並最終會收集垃圾。

「for each」和「for i =」的優缺點已在此討論。對於每一個都很好,因爲它可以與數組以外的結構一起工作,並使對象可用。 「FOR I =」具有指定在環路中的邊界和的數組項順序的優點,並避免了可以用數組遇到錯誤:

Dim a(50) As Integer 
Dim i As Integer 
For Each i In a 
    i = 22 
    Next i 

在本例中,該陣列被從未初始化爲22。變量i只是數組元素的副本,並且當我分配了22時,原始數組元素不會更改。

相關問題