Yield
新しいキーワードのパフォーマンスについて疑問に思っていました。サンプルコードは次のとおりです。
Module Module1
Private test1 As TestClass
Private test2 As TestClass
Private processedValue1 As Integer = 0
Private processedValue2 As Integer = 0
Sub Main()
test1 = New TestClass
test2 = New TestClass
AddHandler test2.OnData, AddressOf TestClass_OnData
Dim s As New Stopwatch
s.Start()
For Each item In test1.GetAllEnum
processedValue1 += 1
Next
s.Stop()
Console.WriteLine("Iterator: " & s.ElapsedMilliseconds)
s.Restart()
test2.Start()
s.Stop()
Console.WriteLine("Event: " & s.ElapsedMilliseconds)
Console.ReadLine()
End Sub
Private Sub TestClass_OnData(sender As TestClass, value As Integer)
processedValue2 += 1
End Sub
End Module
Public Class TestClass
Public Iterator Function GetAllEnum() As IEnumerable(Of Integer)
For i As Integer = 0 To 100000000
Yield i
Next
End Function
Public Sub Start()
For i As Integer = 0 To 100000000
RaiseEvent OnData(Me, i)
Next
End Sub
Public Event OnData(sender As TestClass, value As Integer)
End Class
結果は次のとおりです。
Iterator: 4271
Event: 1028
ご覧のとおり、使用Yield
は従来の実装よりも約 4 倍遅くなります。
とにかくパフォーマンスを向上させる方法はありますか?