c++ - 可以为 lambda 分配名称影响性能吗?
问题描述
直接使用 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})
两者都是一样的。所以没有区别。
推荐阅读
- python-3.x - 为什么我得到一个意外的关键字参数“calculate_hit_box”
- python - 类问题 - 程序按预期工作,但 Visual Studio 代码突出显示语法错误
- python - 无法使用python脚本保存excel文件
- python - 如何在 SentenceTransformers 中设置代理?
- angular - ng build 在 docker(ubuntu)上失败(找不到模块),但在 windows 10 上工作
- vue.js - 无法在 VueJS 中选择带有 v-model 的 chechbox
- webrtc - 将视频从自定义摄像机发布到 antmedia 服务器
- android - 如何在 Android Studio 中获取 Pixel 5 模拟器
- android - 如何在 Android 上显示非整数版本代码
- cognos - 两个日期字段,一个日期过滤器