Reputation: 6981
I found some code like this in a project I'm working on
public SqlDataReader SomeMethod(int someParam)
{
// ... some code goes here
SqlDataReader dataReader = m_command.ExecuteReader(CommandBehavior.CloseConnection);
return dataReader;
}
I was wondering what is better, the original or below
public SqlDataReader SomeMethod(int someParam)
{
// ... some code goes here
return m_command.ExecuteReader(CommandBehavior.CloseConnection);
}
Is there any advantage to creating the variable and then returning it as opposed to just returning the created reader? I would think no as it's just a reference. The example I give was what I found but it could be any variable type. One thing I can think of is during debugging, it's probably nice to look at what's in the variable.
Anybody like to contribute their 2 cents?
Upvotes: 1
Views: 113
Reputation: 138357
Any half-decent compiler will optimise the first example such that dataReader doesn't need to be stored in a temporary variable. In other words, both examples should have the exact same efficiencies.
Personally, I prefer the second (shorter) example as splitting that line over two lines doesn't simplify reading at all.
Upvotes: 1
Reputation: 191925
Debugging is probably the best reason. With the first way, it's easier to e.g. check if dataReader
is null
before returning it.
There really shouldn't be a performance difference, as you said. If this method is invoked often, the JIT compiler (if enabled) is very likely to optimize the local variable away.
Upvotes: 2