Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What about using LINQ or Yield Return in for loops?

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?

like image 741
Rudey Avatar asked Feb 19 '23 03:02

Rudey


2 Answers

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.

like image 55
Dave Avatar answered Mar 04 '23 06:03

Dave


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.

like image 23
Alexei Levenkov Avatar answered Mar 04 '23 05:03

Alexei Levenkov