可以为lambda影响性能指定名称吗?

vld*_*cno 1 c++ performance lambda auto c++11

在直接使用lambda和定义命名的lambda然后将其作为参数传递之间,性能(如果有)有什么不同?

例如:

std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });
Run Code Online (Sandbox Code Playgroud)

与此相对:

auto a_greater_than_b = [](int a, int b) { return a > b; };
std::sort(v.begin(), v.end(), a_greater_than_b);
Run Code Online (Sandbox Code Playgroud)

小智 6

使用gcc 8.2和以下代码:

#include<algorithm>
#include<vector>

int main ()
{
    std::vector<int> v;
    std::sort(v.begin(), v.end(), [](int a, int b) { return a > b; });


    auto a_greater_than_b = [](int a, int b) { return a < b; };
    std::sort(v.begin(), v.end(), a_greater_than_b);
}
Run Code Online (Sandbox Code Playgroud)

无名者的输出:

main::{lambda(int, int)#1}::operator()(int, int) const:
  pushq %rbp
  movq %rsp, %rbp
  movq %rdi, -8(%rbp)
  movl %esi, -12(%rbp)
  movl %edx, -16(%rbp)
  movl -12(%rbp), %eax
  cmpl -16(%rbp), %eax
  setg %al
  popq %rbp
  ret

.....

leaq -48(%rbp), %rax
  movq %rax, %rdi
  call std::vector<int, std::allocator<int> >::end()
  movq %rax, %rbx
  leaq -48(%rbp), %rax
  movq %rax, %rdi
  call std::vector<int, std::allocator<int> >::begin()
  movq %rbx, %rsi
  movq %rax, %rdi
  call void std::sort<__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, main::{lambda(int, int)#1}>(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, main::{lambda(int, int)#1}, main::{lambda(int, int)#1})
Run Code Online (Sandbox Code Playgroud)

并为指定的一个:

main::{lambda(int, int)#2}::operator()(int, int) const:
  pushq %rbp
  movq %rsp, %rbp
  movq %rdi, -8(%rbp)
  movl %esi, -12(%rbp)
  movl %edx, -16(%rbp)
  movl -12(%rbp), %eax
  cmpl -16(%rbp), %eax
  setl %al
  popq %rbp
  ret

.....

leaq -48(%rbp), %rax
  movq %rax, %rdi
  call std::vector<int, std::allocator<int> >::end()
  movq %rax, %rbx
  leaq -48(%rbp), %rax
  movq %rax, %rdi
  call std::vector<int, std::allocator<int> >::begin()
  movq %rbx, %rsi
  movq %rax, %rdi
  call void std::sort<__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, main::{lambda(int, int)#2}>(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, main::{lambda(int, int)#2}, main::{lambda(int, int)#2})
Run Code Online (Sandbox Code Playgroud)

两者都是一样的.所以没有区别.