Anis Alibegić
Anis Alibegić

Reputation: 3230

Performance wise difference between returning direct initialization and storing in variable

Is there any difference (performance wise) between:

public User GetUser1()
{
    var user = _database.User.First();
    return user;
}

public User GetUser2()
    return _database.User.First();
}

Upvotes: 1

Views: 51

Answers (1)

NetMage
NetMage

Reputation: 26917

Here is the output from LINQPad for C# 7.0 from the same functions on my database:

GetUser1:
IL_0000:  ldarg.0     
IL_0001:  call        LINQPad.User.TypedDataContext.get_Users
IL_0006:  call        System.Linq.Queryable.First<User>
IL_000B:  ret         

GetUser2:
IL_0000:  ldarg.0     
IL_0001:  call        LINQPad.User.TypedDataContext.get_Users
IL_0006:  call        System.Linq.Queryable.First<User>
IL_000B:  ret         

Here is the output with optimization turned off. Note the NOPs and BR.S are for debugging/breakpoint purposes.

GetUser1:
IL_0000:  nop         
IL_0001:  ldarg.0     
IL_0002:  call        LINQPad.User.TypedDataContext.get_Users
IL_0007:  call        System.Linq.Queryable.First<User>
IL_000C:  stloc.0     // user
IL_000D:  ldloc.0     // user
IL_000E:  stloc.1     
IL_000F:  br.s        IL_0011
IL_0011:  ldloc.1     
IL_0012:  ret         

GetUser2:
IL_0000:  nop         
IL_0001:  ldarg.0     
IL_0002:  call        LINQPad.User.TypedDataContext.get_Users
IL_0007:  call        System.Linq.Queryable.First<User>
IL_000C:  stloc.0     
IL_000D:  br.s        IL_000F
IL_000F:  ldloc.0     
IL_0010:  ret         

Upvotes: 2

Related Questions