Saturday, July 25, 2015

How can I minimise memory thrashing when doing vector math in C# or C++?


I'm doing a lot of 3D math in my game engine loop using typical classes like Vector3D, Matrix4x4, Plane3D, etc. Currently every operation causes a new object to be created for the result value. The number of new objects created causes a stutter whenever the GC kicks in.


In this simple vector operation, 2 new Vector3D objects are created, one at the divide and one at the multiply operator.


// C#
result = (v / len1) * len2; // where len* is a `double`


I happen to know some C++, so an optimized version would create a disposable object on the stack and pass that to the individual ops, thereby automatically disposing off the temporary objects at the end of the function (also avoiding the GC altogether), something like this:


// C++
Vector3D result;
v.divideBy(len1, &result);
result.multiplyBy(len2, &result);

But as you can see its cumbersome and unreadable. So what are commonly used memory optimization strategies used by pro C++ gamedevs to optimize vector math? I'm looking for general platform agnostic solutions that can be implemented in C# and other high-level languages, although C++ memory tricks are also appreciated.



Answer



Are you sure that the matrix operations are causing the slowdown? In C# most Vector libraries implement their types as structures, which are not generally allocated using the garbage collector, but are instead created on the stack. The temporaries in your example don't cause allocations that need to be collected.



No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...