c++ - 为 lambda 分配名称会影响性能吗?

标签 c++ performance c++11 lambda auto

直接使用 lambda 和定义命名 lambda 然后将其作为参数传递在性能方面有什么区别(如果有的话)?

例如这个:

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);

最佳答案

使用 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);
}

匿名者的输出:

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})

对于命名的那个:

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})

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

关于c++ - 为 lambda 分配名称会影响性能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52086897/

相关文章:

c++ - C++中为什么可以继承接口(interface)

c++ - 程序使用 clang++ 编译,但 g++ 耗尽 RAM 并失败

c++ - 从 C++14 切换到 C++11 时修复的对 boost::system::detail::system_category_instance 的 undefined reference

c++ - 多行原始字符串文字作为预处理器宏参数

c++ - 为什么 const 数组不能从 constexpr 函数访问?

c++ - lambda:应该通过引用捕获 const 引用产生未定义的行为吗?

c++ - 将 Clips 嵌入到 C 中和将 Clips 嵌入到 C++ 中的不同之处

php - 如何使网站的第一部分首先加载? (就像在 Google PageSpeed 中一样)

MySQL 选择查询在使用 where 和降序时变得非常慢

mysql - 查找表的高效索引