In C#, lambda can access local variable, and also return some data.
then, which is better in following situation?
int num;
Func<int> func = ()=>{return 10;}
num = func();
vs
int num;
Action action = ()=>{num = 10;}
I think, the performance is different.
Which is better?
UPDATE(I dont know how to use StackOverflow)
My code here.
ErrorCode errorCode;
errorCode = DatabaseUtility.Read<ErrorCode>(
conn,
DatabaseUtility.CreateSelectQuery(....),
reader =>
{
if(reader.Read())
return ErrorCode.None;
return ErrorCode.InvalidParam;
});
But in this case, may be I can do like this.
ErrorCode errorCode;
DatabaseUtility.Read(
conn,
DatabaseUtility.CreateSelectQuery(....),
reader =>
{
if(reader.Read())
errorCode = ErrorCode.None;
else
errorCode = ErrorCode.InvalidParam;
});
And, this is the method definition.
public static class DatabaseUtility
{
public static Read<T>(
MySqlConnection conn,
string query,
Func<MySqlDataReader, T> callback);
}
Gibbo is right: returning the value is clearer, so you should use that and not worry about performance, unless this code is in the 3% of code when microoptimizations make sense.
But returning the can also be more efficient, because it doesn't require heap allocation for the closure object and because it means num
is going to be compiled as a local variable, not a field on the closure object (accessing local variables is cheaper than fields).
Also, if you're going to return the value, there is no reason to declare the variable so early, which will make your code slightly shorter:
Func<int> func = ()=>{return 10;}
int num = func();
The first one is better designed. It is reusable and can be called again and again on different variables (if required).
Performance I am not sure of, most likely negligible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With