I made a blatantly stupid logic mistake the other day in a business logic layer method that I was writing and got the following exception: “Collection was modified; enumeration operation may not execute.” The problem what I was trying to remove an object from a collection while I was enumerating through it using a FOREACH statement. After I realized what I had done I solved the problem by populating a new collection with a little bit of LINQ.
There were several solutions I could have used to solve the problem; specifically I could have used a FOR loop, multiple FOREACH loops or the LINQ solution that I posted above (and there are probably more solutions that I haven’t thought of.) This led me to wonder about the performance for each solution, which in turn led me to this post: http://frater.wordpress.com/2008/02/20/collection-was-modified-enumeration-operation-may-not-execute/
FOR – FOREACH – LINQ Performance Tests
My system specs:
- Intel Core 2 Duo 2.5 GHz
- 4 GB memory
- Windows Vista Enterprise 64bit
- .NET Framework 3.5 SP1
After reading through the post above and the comments that it was followed by, I decided to test all three solutions to see what the speed was like. The results surprised me by quite a lot. I knew LINQ was somewhat slow, but I didn’t realize exactly how slow until I ran these tests.
So yeah, LINQ is considerably slower than using a FOR loop in this instance. However, I would personally still use LINQ in instances where I am working with a small amount of data and the performance difference is negligible. Why? Because in my opinion LINQ is much easier to read, understand & lends itself to fewer bugs.
Performance Test Application Download
You can download and run the performance test that includes implementations of each solution I mentioned above from the link below.