Search code examples
c#optimizationclr

Does putting less number of curly braces really helps?


What if do not use a curly braces after an if statement. Like :-

if(SomeCondition())
    return true;

Instead of

if(SomeCondition())
{
  return true;
}

Does it really help the compiler be it in terms of compilation time, better IL code generation, accquires less space or any other aspect (which at this point I am really not able to think of) ? Would like to know does it really help or is it just about code readability ?


Solution

  • They do the same.
    The MSIL code will be almost the same in both cases if your'e in debug mode(Thanks Dirk).
    In release mode the MSIL will be the same.

    Here's a linqpad example(debug mode):

    Example1:
    C#:

    void Main()
    {
        bool a = true;
        int i;
        if(a)
         i = 17;  
    }
    

    IL:

    IL_0001:  ldc.i4.1    
    IL_0002:  stloc.0     // a
    IL_0003:  ldloc.0     // a
    IL_0004:  ldc.i4.0    
    IL_0005:  ceq         
    IL_0007:  stloc.2     // CS$4$0000
    IL_0008:  ldloc.2     // CS$4$0000
    IL_0009:  brtrue.s    IL_000E
    IL_000B:  ldc.i4.s    11 
    IL_000D:  stloc.1     // i
    

    Example2:

    C#:

    void Main()
    {
        bool a = true;
        int i;
        if(a)
        {
         i = 17;  
        }
    }
    

    IL:

    IL_0001:  ldc.i4.1    
    IL_0002:  stloc.0     // a
    IL_0003:  ldloc.0     // a
    IL_0004:  ldc.i4.0    
    IL_0005:  ceq         
    IL_0007:  stloc.2     // CS$4$0000
    IL_0008:  ldloc.2     // CS$4$0000
    IL_0009:  brtrue.s    IL_0010
    IL_000B:  nop         
    IL_000C:  ldc.i4.s    11 
    IL_000E:  stloc.1     // i