Memory Allocation Cost

In the tutorials for Memory Management, there is an section Memory Allocation Cost regarding optimizing locals, particularly, in a for loop.

This contradicts what i had been lead to believe in that the compiler will optimize an optimal variable allocation inside of the loop, there is SO thread about it that summarizes much better than i:

Basically the results are shown that an optimization such as in the above tutorial is otherwise unnecessary, at least using the non TinyCLR tool chain.

Is there an actual difference we should expect in optimization with TinyCLR? From what i understand the optimization might be valid in native c/++ code, but that’s off topic.

I actually know this now (i think)…

To my knowledge, TinyCLR is running on an interpreter under the hood rather than native compiled code, so the compiler actually won’t optimize this the way it says in the link.

Feel free to correct me if i’m wrong.

Correct, the PC compiles the IL and does more magic beyond what the C# compiler does. It is better to be on the safe side regardless.

I see so due to the interpreter, optimizations are not done.
Understanding now there is an interpreter I see I must reconsider some things i thought i knew.

There is a big difference between the guidance in the GHI document link and the softwareengineering link.

The softwareengineering link shows stack variables, and the GHI docs use the ‘new’ operator. The two behave very differently. The guidance to initialize and reuse a single allocation using ‘new’ is very important for avoiding needless memory churn on the heap. However, the softwareengineering example is dealing with stack (not heap) allocations, so the only cost here is the execution (time) cost of moving the stack pointer repeatedly rather than once.

Both are good guidance, but the minimization of ‘new’ in loops is an essential best practice for TinyCLR programs (and arguably all managed-code programs).