Currently I'm working on a 2D XNA game. It needs optimizing, because the multiplayer mode is not performing well. In code we have mostly used foreach loops, and have not used LINQ or yield return statements anywhere. I understand we can win some performance here. Since for loops are faster, I was thinking of replacing all foreach loops.
But, however, I can't benefit from the yield return statement in a for loop, can I?
Also, will LINQ still be useful when iterating using a for loop?
For example, I have a list of 1000+ shapes (squares, triangles, circles...), and I want to enumerate through all squares (75%) at a certain position. What's the best way of doing this?
What should I use? Arrays, lists, for loops, foreach loops, yield return and/or LINQ?
Do any grouping or sorting you need to do as items are added, not as they are retrieved. I say this because you'll (I assume) only add each item once, but as you say you're retrieving them multiple times.
Since it is performance question the only right answer is measure.
In general directly using for
will likely be the fastest approach as the rest add more code for each iteration. Try and measure yourself - see if it matters in your case and which version of code you like to read the most.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With