Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# optimization - arrays / lists of value types and the stack (gaming)

I'm working on a game and am in the middle of a bit of AI number crunching and I want to optimize the code as much as I can. I have several structs in my code like Circle, Vector, etc. I want to reduce to a minimum the load on the GC as a result of this code since it will run many times a second and in each invocation will generate several large arrays and perform a lot of computations.

My question is, if I have a small method that can "return" multiple value types (i.e intersection of circle and vector, etc), what is the most performant way to transfer its result back to the main method?

I can think of a few ways to do it:

  • Return an array of the results i.e Vector[ ]
  • Return a List<Vector>
  • Pass in a List<Vector>
  • Any other way..?

What would be the best strategy to avoid a lot of small unnecessary objects / arrays on the heap that the GC then has to collect?

like image 544
Amir Abiri Avatar asked Jan 17 '23 15:01

Amir Abiri


1 Answers

If you're in a situation where:

  • You're calling this method very frequently
  • You'll always be dealing with the same size of collection (or similar, at least)
  • You don't need the previous results by the time you next call it

... then you may be able to improve performance by repeatedly passing in the same array (or List<T>) and modifying it. On the other hand, you should absolutely measure performance before making any changes. You should also determine what's going to be "good enough" so you don't bend your code away from the most natural design any more than you have to.

like image 199
Jon Skeet Avatar answered Jan 26 '23 00:01

Jon Skeet