0

Suppose I have some code looking like this :

void doTasksAndStuff()
{
    // Do stuff
    ...

    // Do task
    ...

    // Do stuff
    ...

    // Do same task
    ...

    // Do stuff
    ...
}

Since the task is done twice, I suppose it is better to factor the corresponding code :

void doTask()
{
    // Do task
    ...
}

void doTasksAndStuff()
{
    // Do stuff
    ...

    doTask();

    // Do stuff
    ...

    doTask();

    // Do stuff
    ...
}

Now, what if I wrote it like this :

void doTasksAndStuff()
{
    auto doTask = []()
    {
        // Do task
        ...
    };


    // Do stuff
    ...

    doTask();

    // Do stuff
    ...

    doTask();

    // Do stuff
    ...
}

Since doTask() is only called in the function doTasksAndStuff(), it seems to me to be a clean way of factoring the code without polluting any namespace, but is that the only difference between those two ways of factoring?

In particular, what about performance? What about inlining?

joce
  • 9,624
  • 19
  • 56
  • 74
Eternal
  • 2,648
  • 2
  • 15
  • 21

1 Answers1

0

Performance should be about the same. The big advantage (and difference) with lambdas is that you can capture local variables in a closure. If you did it as a named function, then you'd have to pass all local variables that are used in your task.

Note that another way to do this is with a local struct, which you can kind of think of as a poor-man's lambda.

kec
  • 2,099
  • 11
  • 17
  • Thanks for your answer, but my question is more about functors than it is about lambdas. Will the compiler be able to inline the code in the functor if no local variable is captured? Does the answer change if a local variable is captured? – Eternal May 04 '14 at 09:27
  • Q1: Yes, see this: http://stackoverflow.com/questions/13722426/why-can-lambdas-be-better-optimized-by-the-compiler-than-plain-functions. Q2: No more than using a separate function. – kec May 04 '14 at 12:29