Search code examples
c#performancexnanew-operator

Performance cost of 'new' in C#?


In C# what is the performance cost of using the new keyword? I ask specifically in relation to games development, I know in C++ it is a definite no-no to be newing things every update cycle. Does the same apply to C#? I'm using XNA and developing for mobile. Just asking as an optimization question really.


Solution

  • There are three parts to the cost of new:

    • Allocating the memory (may not be required if it's a value type)
    • Running the constructor (depending on what you're doing)
    • Garbage collection cost (again, this may not apply if it's a value type, depending on context)

    It's hard to use C# idiomatically without ever creating any new objects in your main code... although I dare say it's feasible by reusing objects as heavily as possible. Try to get hold of some real devices, and see how your game performs.

    I'd certainly agree that micro-optimization like this is usually to be avoided in programming, but it's more likely to be appropriate for game loops than elsewhere - as obviously games are very sensitive to even small pauses. It can be quite hard to judge the cost of using more objects though, as it's spread out over time due to GC costs.

    The allocator and garbage collector is pretty good in .NET, although it's likely to be simpler on a device (Windows Phone 7, I assume)? In particular, I'm not sure whether the Compact Framework CLR (which is the one WP7 uses) has a generational GC.