3

Actually, I am familiar with memory model of .NET framework.

I am interested in knowing if the JIT compiler could place local variables in CPU registers to improve the performance of the application, instead of allocating variables on the stack? If it can, what are the requirements for such an allocation and how does it decide whether or not to perform it?

Martin Törnwall
  • 9,299
  • 2
  • 28
  • 35
frankie
  • 728
  • 1
  • 10
  • 28
  • 4
    It is one of the standard optimizations performed by the jitter optimizer. Nothing you need, or can, do on your end, other than making sure you deploy the Release build. [This post](http://stackoverflow.com/questions/4043821/performance-differences-between-debug-and-release-builds/4045073#4045073) has the background story on the optimizer. – Hans Passant Jan 06 '15 at 13:48

1 Answers1

3

This is being done all the time by the JIT. It is a standard optimization for pretty much any JIT and native compiler.

Don't confuse the logical IL stack with the physical x86 stack that the jitted code uses. They are very weakly related. IL stack contents and IL locals are being stored preferably in registers and spilled to the x86 stack only if needed.

The only exception are structs which are usually stack-allocated in both the .NET 4.5 JIT and the vNext RyuJIT (as of VS2015 Preview). This is not documented but testing clearly shows that not even in the simplest cases structs are being enregistered. Maybe I missed some case where it happens but it is clearly a rare case.

Primitive types and object references are consistently stored in registers (if available) according to my testing.

usr
  • 168,620
  • 35
  • 240
  • 369