Creating local variables in .Net

I just want to know that creating local variables to accept the return value of a function will result in memory usage or performance in .Net applications, especially in ASP.Net.

they say

MyObject myObject = Foo(); MyOtherObject myOtherObject = Boo(); SomeFuntion(myObject, myOtherObject); 

OR

Should i use

  MyFunction(Foo(), Boo()); 

Of course, the previous use has better readability. But what about memory usage and performance?

Thanks in advance 123Developer

+4
source share
4 answers

Do not optimize prematurely; in the release build, it is likely that the compiler will optimize them anyway! In any case, you are just talking about a small amount of stack space for (presumably) multiple links. Any approach is perfect; go whichever is more readable.

+15
source

CIL (the intermediate language in which C # is compiled) is a stack-based language, so the return values ​​of intermediate functions must end on the stack before being passed as arguments to the final one.

There is no way to predict what the C # compiler will do [1] in terms of locals; he may decide to use the locals when you do this, or he may use the behavior of the stack and generally skip them. In the same way, it can be synthesized by local residents, even if you do not use them, or it may not be so.

In any case, the difference in performance is not worth the worry.


[1] Yes, of course, you can compile and look at the IL that it produces to determine what it will do, but this is true only for the current version of the compiler, using and which is an implementation detail that cannot be relied on.

+5
source

I believe that the memory performance will be almost the same. And if performance testing did not show a significant difference, choose the option with improved readability.

+2
source

Do not be afraid to use local variables. The difference in memory usage and performance is very small or, in some cases, completely absent.

In your particular case, local variables can use 8 bytes (16 bytes in a 64-bit application) of the stack space. However, the compiler can create local variables on its own, if necessary for temporary storage, therefore, in either case, both versions have the same set of local variables.

In addition, the compiler can use processor registers instead of the stack space for some local variables, so it’s not even sure that creating a local variable actually uses any stack space in general.

Stack space allocation is very cheap. When a method is called, a stack stack is created for local data in the method. If you need to allocate more memory, this will only change how the stack pointer moves; it does not generate any additional code at all.

So, just write code to be robust and reliable, and trust the compiler to optimize the use of the variable.

0
source

All Articles