else or return?

后端 未结 19 916
故里飘歌
故里飘歌 2021-01-01 13:27

Which one out of following two is best wrt to performance and standard practice. How does .NET internally handles these two code snippets?

Code1

If(r         


        
19条回答
  •  长情又很酷
    2021-01-01 14:00

    They will both compile into the same IL for Release mode (there may be a few different Nop operands in Debug..) And as such will have no performance difference. This is totally up to how you and your team feel the code is easier to read.

    I used to be in the camp against early exit, but now I feel it can make code much simpler to follow.

    // C#
    public static void @elseif(bool isTrue)
    {
        if (isTrue)
            Process1();
        else
            Process2();
    }
    // IL
    .method public hidebysig static void  elseif(bool isTrue) cil managed
    {
      // Code size       15 (0xf)
      .maxstack  8
      IL_0000:  ldarg.0
      IL_0001:  brfalse.s  IL_0009
      IL_0003:  call       void elseif.Program::Process1()
      IL_0008:  ret
      IL_0009:  call       void elseif.Program::Process2()
      IL_000e:  ret
    } // end of method Program::elseif
    
    
    // C#
    public static void @earlyReturn(bool isTrue)
    {
        if (isTrue)
        {
            Process1();
            return;
        }
        Process2();
    }
    // IL
    .method public hidebysig static void  earlyReturn(bool isTrue) cil managed
    {
      // Code size       15 (0xf)
      .maxstack  8
      IL_0000:  ldarg.0
      IL_0001:  brfalse.s  IL_0009
      IL_0003:  call       void elseif.Program::Process1()
      IL_0008:  ret
      IL_0009:  call       void elseif.Program::Process2()
      IL_000e:  ret
    } // end of method Program::earlyReturn
    

提交回复
热议问题