I want to inline a lambda expression since it is very short for performance reason. Is it possible?
The inline
keyword does not actually cause functions to be inlined. Any recent compiler is going to make better decisions with regards to inlining than you will.
In the case of a short lambda, the function will probably be inlined.
If you're trying to use the inline
keyword with a lambda, the answer is no, you can't use that.
It is possible that a lambda expression might be inlined. Under the hood, a lambda expression is no different than any other function object.
Whether a particular lambda expression is inlined is entirely dependent upon the compiler and whether it decides it is worth inlining.
If you have a regular struct functor, the compiler will almost certainly inline it. If you have a C++0x style lambda, the compiler will almost certainly inline it. If you're using a boost::lambda, then it might do, depending on how the lambda works underneath the scenes. Short version: You can't guarantee it's inlining or non-inlining, but you should trust your compiler and if in doubt, make it easy and simple to inline.
I haven't looked at the output from a lot of them by any means, but so far all of them I've looked at the output from have been inlined.
C++1x' lambdas will, under the hood, generate normal function objects. Those can be inlined by the compiler.
Did any measurements you made suggest the compiler did not inline them in a place where this leads to a notable performance loss?
The compiler will inline it if it can. For example, in g++ 4.5 with -O2,
#include <vector>
#include <algorithm>
int main () {
std::vector<int> a(10);
for (int i = 0; i < 10; ++ i) a[i] = i;
asm ("Ltransform_begin: nop; nop; nop; nop; nop; nop; ");
std::transform(a.begin(), a.end(), a.begin(), [] (int x) { return 2*x; });
asm ("Lforeach_begin: nop; nop; nop; nop; nop; nop; ");
std::for_each(a.begin(), a.end(), [] (int x) { printf("%d\n", x); });
asm ("Lforeach_done: nop; nop; nop; nop; nop; nop; ");
return 0;
}
generates the assembly that the 2*x
and printf
lambdas are completely inlined.
# 9 "x.cpp" 1
Ltransform_begin: nop; nop; nop; nop; nop; nop;
# 0 "" 2
.align 4,0x90
L13:
sall (%rax)
addq $4, %rax
cmpq %rax, %r12
jne L13
# 13 "x.cpp" 1
Lforeach_begin: nop; nop; nop; nop; nop; nop;
# 0 "" 2
.align 4,0x90
L14:
movl (%rbx), %esi
leaq LC0(%rip), %rdi
xorl %eax, %eax
LEHB1:
call _printf
LEHE1:
addq $4, %rbx
cmpq %r12, %rbx
jne L14
# 17 "x.cpp" 1
Lforeach_done: nop; nop; nop; nop; nop; nop;
# 0 "" 2