Performance comparison of IEnumerable and raising event for each item in source?

后端 未结 1 1499
-上瘾入骨i
-上瘾入骨i 2021-01-07 02:33

I want to read big binary file containing millions of records and I want to get some reports for the records. I use BinaryReader to read (which I think has the

相关标签:
1条回答
  • 2021-01-07 03:05

    Yes, using Iterator Functions carries a performance penalty.

    I compiled your code and I got the same results as you did. I looked at the generated IL code. The state machine created from the GetAll method does contain a lot of stuff but most of the instructions are nop's or simple operations.

    The results with/without using the iterator functions differ, as you say, by 25%. That's not too much. When you are using StartReadBinary, there is simply one big cycle which calls the OnByteRead method (via the event) three billion times. However, when you create the objects in a foreach cycle, what you must do for each object is call the GetCurrent() method and MoveNext() of the generated enumerator, the latter of which is not trivial (most of the code from GetAll was moved there) and uses quite an amount of compiler-generated variables.

    Using "Yield" generally slows down your program because the compiler has to create complicated IL code to represent the state machine.

    0 讨论(0)
提交回复
热议问题