Memory and processing - Variables and verification

1

Is there a big difference for memory and processing in how to run the check in these two examples? If yes, why and how both behave at the time of executing the codes.

Method 1:

var exam = FindExamByID(id);

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

Method 2:

if (FindExamByID(id) == null)
{
    return NotFound();
}
    
asked by anonymous 10.08.2017 / 16:13

3 answers

2

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

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 given in

10.08.2017 / 17:26
0

Not the difference, the difference a is only in reading the code. Many programmers prefer to put the return of a function on a variable before doing some processing with it, some already prefer to use the function directly, but in this particular case it will not have any difference.

    
10.08.2017 / 16:16
0

It makes no difference if you're compiling using Release mode (with optimize code enabled), which should be used for production environment. In both cases, the Intermediate Language code generated by the compiler 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 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;
        }
    }
    
10.08.2017 / 16:35