简体   繁体   中英

What is the difference between following cases?

Code is in C#

Case 1

var p = new Person();
p = getPerson(p); 

Case 2

var p = new Person();
getPerson(p);

In above cases, will any case consume extra memory?

Assuming getPerson just modifies properties of the Person and there are 2 different methods one that returns a person and one that is void, there is no appreciable difference in this code

static void Main(string[] args)
{

   // example 1
   var p = new Person();
   p = getPerson1(p);

   // example 2
   var p2 = new Person();
   getPerson2(p2);
}

Example 1

IL_0001: newobj       instance void ConsoleApp8.Person::.ctor()
IL_0006: stloc.0      // p

// [33 10 - 33 28]
IL_0007: ldloc.0      // p
IL_0008: call         class ConsoleApp8.Person ConsoleApp8.Program::getPerson1(class ConsoleApp8.Person)
IL_000d: stloc.0      // p

Example 2

IL_000e: newobj       instance void ConsoleApp8.Person::.ctor()
IL_0013: stloc.1      // p2

// [36 4 - 36 19]
IL_0014: ldloc.1      // p2
IL_0015: call         void ConsoleApp8.Program::getPerson2(class ConsoleApp8.Person)
IL_001a: nop          

OpCodes.Stloc Field

Pops the current value from the top of the evaluation stack and stores it in a the local variable list at a specified index.

OpCodes.Nop Field

Fills space if opcodes are patched. No meaningful operation is performed although a processing cycle can be consumed.


In short, worry about other things

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM