Memory and processing - Variables and verification

Asked

Viewed 62 times

1

Is there a big difference for memory and processing in how to perform the verification in these two examples? If yes, why and how they both behave when executing the codes.

Method 1:

var exam = FindExamByID(id);

if (exam == null)
{
    return NotFound();
}

Method 2:

if (FindExamByID(id) == null)
{
    return NotFound();
}

3 answers

2


I made a comparison with the two forms just to prove it. The first:

IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: ldloc.0
IL_0004: call instance string C::FindExamByID(int32)
IL_0009: brtrue.s IL_0012
IL_000b: ldarg.0
IL_000c: call instance int32 C::NotFound()
IL_0011: ret
IL_0012: ldc.i4.1
IL_0013: ret

The second:

IL_0000: ldc.i4.1
IL_0001: stloc.0
IL_0002: ldarg.0
IL_0003: ldloc.0
IL_0004: call instance string C::FindExamByID(int32)
IL_0009: brtrue.s IL_0012
IL_000b: ldarg.0
IL_000c: call instance int32 C::NotFound()
IL_0011: ret
IL_0012: ldc.i4.1
IL_0013: ret

Can be checked in Sharplab.

Is the same bytecode so it has no different in processing or memory consumption, in this case. I cannot guarantee that in any case an optimization occurs in a way that is not possible in the other way. Composed of other parts the generated code can be a little different and there is a difference. A simple reordering of instructions can make the processing have another commitment.

The .maxstack 2 equal in both shows that the fact that there is a variable to support the value does not change anything when compared to the slot in the stack frame required for value without variable.

0

Not the difference, the difference is only in reading the code. Many programmers prefer to put the return of a function in a variable before doing some processing with the same, some already prefer to use the function directly, but in this specific case there will be no difference.

0

It makes no difference if you are compiling using the mode Release (with optimize code enabled), which should be used for production environment. In both cases, the code Intermediate Language generated by the compiler is what is described below.

.method private hidebysig static void  Main(string[] args) cil managed
{
  .entrypoint
  // Code size       8 (0x8)
  .maxstack  8
  IL_0000:  ldc.i4.0
  IL_0001:  call       object MetodosTeste.Program::FindExamById(int32)
  IL_0006:  pop
  IL_0007:  ret
} // end of method Program::Main

The pseudo-code used to generate the IL above was this:

 class Program
    {
        static void Main(string[] args)
        {
            int id = 0;

            //var exam = FindExamById(id);

            if (FindExamById(id) == null)
                return;
        }

        static object FindExamById(int id)
        {
            return int.MinValue;
        }
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.