Function-level GC-related static/runtime constraint checks?


#1

Motivation:
Certain performance-critical code, particularly in realtime/simulation/physics/game development, must ensure certain sections of their code do not allocate new memory. Example: Farseer PhysicsPhysics engines like Farseer Physics, written in pure C#, often take great pains to ensure that no new allocations happen during the performance critical phases of physics simulation (collision detection, integration, etc…). These sections of code must not allocate memory in order to ensure reliable realtime performance. Currently, the developers must use a profiler to check for allocations.

Proposed solution:
A [NoAllocate] annotation which, when applied to a function, turns on a constraint check that ensures no new allocations happen in any code-paths within the function. For example, in Farseer Physics, this attribute would be applied to the collision detection and integration step functions to ensure that they do not cause new allocations.

Static vs runtime constraint checking:
Static checking would be preferable, if feasible. Otherwise even a dynamic runtime check would be useful.

Potential issues:
This would produce a false-positive for code that amortizes allocations dynamically. For instance, a particle system that dynamically grows its particle memory pools as the number of particles grows.


#2

Wouldn’t an analyzer be enough? Maybe something similar to this one?


#3

Thanks for the link! Yes, I think an analyzer would be enough, though it may not work across multiple languages. The one linked would need the ability to annotate the code such that allocations in non-critical sections are ignored and allocations in critical sections are errors. Currently it appears to show all allocations in the entire application as warnings only, with no way to filter.


#4

The one linked would need the ability to annotate the code such that allocations in non-critical sections are ignored and allocations in critical sections are errors. Currently it appears to show all allocations

I’m one of the developers on that project (although the majority of the work was done by @mjsabby). But when I have some time, the plan is to see how the functionality you are asking for could be added, it’s something I’ve thought about before.

The current thinking is the use of a [HotPath] attribute to indicate which methods it should be applied to.


.NET Foundation Website | Blog | Projects | Code of Conduct