Performance cost of 'new' in C#?

The cost of the new operator itself is negligible. What might cost is the processing that happens in a custom constructor. So if you have lots of things going on in this constructor it could be a problem.


Allocation in C# is actually faster than in C++. It just involves increasing the heap pointer and returning that pointer. Generally, objects get newed up more often in C# than in C++, as there is a bit more immutability involved in things like strings.

As others have pointed out, the real beast is the garbage collector, which is a bit tricky to profile. Nonetheless, even GCing is in most cases just as fast if not faster than delete in C++ -- just that you can't predict when it'll happen.

Some hints by Rico Mariani, the perf guy on the .NET team: http://msdn.microsoft.com/en-us/library/ms973837.aspx

It's a bit old and there have been a few improvements on the GC, but most of the information is still relevant.

I should add though that the XNA/Compact Framework Garbage Collector is somewhat slower than in the x86 version to trade off CPU for memory performance, so you should beware of that.

EDIT

I forgot to mention, and this is important: value types, including structs, use the new syntax too, but they're created on the stack rather than on the heap, so there's no GC cost for those unless you box them.


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.