我想知道新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 倍。
有没有办法提高性能?