Less allocation == Optimised code
In programming world, broadly there are two memories. One is stack and other is heap. In garbage collector based language, heap memory is taken care by garbage collector(GC). Stack doesn’t need GC, allocations are freed up as soon as end of the stack is reached. More allocation, more pressure on GC to clean the heap and it affects the performance. So Sumeet, you are saying stack is best choose? It is but stack comes with a limitation i.e size of stack is fixed . Heap can allocate large arrays but if you try to do that with stack then you will get classic stackoverflow error.
Okay Sumeet! why we are discussing so much on memory type. The thing is if we want to execute something from heap, the thing is not immediately available. We have to go through a indirection. There is a table like structure which constantly updates and store which object is where on the heap(basically stores the address). Whereas if something is on stack, there are no indirection.
Hence when you are writing performance critical application, taking these two points into consideration will be crucial.
Let’s take an example in C#, we want to multiple two numbers. One way of doing is by defining a lambda(delegate) method and other way of doing is using location functions. Interesting part is local function can be represented in the form of struct which is stack allocation. Now based above two points and an interesting fact, we can theoretically say the method with local function will execute faster than lambda version and same is confirmed by benchmark result.
Earlier, I spoke about indirection. From above image, we can see two highlighted IL instructions — one is call and other is callvirt. Callvirt instruction is the one which doesn’t directly call the method/object but checks the address of the object in table structure and then call it(also does null checks in some cases). This is the indirection and we get performance penalty due to which.
Hope you enjoyed reading this post. This post was inspired from this stackoverflow question
~ Happy Coding.