Defining Lambda function inside a loop

Does defining a lambda function inside a while loop have a meaningful performance impact vs defining it outside of the loop?

A:

While (){
auto foo = [&] {}
foo();
}

vs

auto foo = [&] {}

While (){
foo();
}

For the example you gave, I expect the optimizer to figure this out. Though if you have captures by value, the copy constructor needs to run. So to optimize that, the compiler needs visibility of all that code and be able to prove no side effects occur in order to extract that info out of the loop.

1 Like

Thanks JVApen! I appreciate you taking the time to answer my question. Do you happen to know where I can find documentation to learn more about this topic?

I like this presentation by Chandler: https://youtu.be/FnGCDLhaxKU?si=Fv9WTlf9SujuscUS