Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# lambda, assign local variable vs return data

Tags:

c#

lambda


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);
}
like image 982
Won Hyoung Lee Avatar asked Mar 08 '15 14:03

Won Hyoung Lee


2 Answers

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();
like image 127
svick Avatar answered Sep 22 '22 21:09

svick


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.

like image 30
Gibbo Avatar answered Sep 22 '22 21:09

Gibbo