如果 operator!=() 使用 operator==() 的否定,我应该内联运算符 == 和 !=

如何解决如果 operator!=() 使用 operator==() 的否定,我应该内联运算符 == 和 !=

我用这个简单的例子来说明我试图优化堆栈使用的问题。假设我有一个这样的结构:

// Something.h
struct Something {
  int val;

  bool operator==(const Something& rhs);
  bool operator!=(const Something& rhs);
};

// Something.cpp
bool Something::operator==(const Something& rhs) {
  return val == rhs.val;
}

bool Something::operator!=(const Something& rhs) {
  return !(*this == rhs);
}

调用 operator!=() 会将两个堆栈帧压入堆栈(一个用于 !=,另一个用于 ==)。 我应该内联 operator!=() 以便 == 和 != 使用相同数量的堆栈吗?

解决方法

您应该使用链接时优化 (LTO),这样它们中的任何一个都可以完全内联到调用站点,尤其是当它像这样几乎微不足道时。

但是如果您不想使用 LTO 进行跨文件内联,那么将 operator != return !(*this == rhs); 定义放在.h),因此每个调用者都可以看到它,并且可以将其内联到仅包含 .h 的文件中。然后调用者的 asm 将调用相同的 operator== 定义,但以相反的方式使用结果。例如test al,al / jnz 而不是 jz 如果您要对结果进行分支。

如果您不使用 LTO 并且不使定义对编译时内联可见,那么最好的情况是编译器会将 operator== 内联到 operator!= 独立定义中在编译那个 .cpp 时。然后你在机器代码中有两个相似大小的函数,它们只有一个布尔反转。这些函数的用户(来自其他文件)将调用其中一个,因此它们都占用了您的 I 缓存/代码占用空间。


示例

https://godbolt.org/z/e88nGj

// Something.h
struct Something {
  int val;

  bool operator==(const Something& rhs);
  bool operator!=(const Something& rhs) { return !(*this == rhs); }
};
// simulated #include for one-file demo purposes

// Some other .cpp file,operator== definition not visible.
int foo(Something &a,Something &b)
{
    if (a != b) {
        return a.val;
    } else { 
        return b.val;
    }
}

GCC -O3 for x86-64 (Godbolt) 编译如下:

foo(Something&,Something&):
        push    rbp
        mov     rbp,rsi
        push    rbx
        mov     rbx,rdi           # save the pointers in call-preserved regs
        sub     rsp,8
        call    Something::operator==(Something const&)
        test    al,al                # set FLAGS from the bool retval
        cmovne  rbx,rbp              # select the right pointer
        mov     eax,DWORD PTR [rbx]  # and load from it

        add     rsp,8                # epilogue
        pop     rbx
        pop     rbp
        ret

请注意,这段代码调用了 Something::operator==,它在编译时无法内联(它可以在与 LTO 的链接时内联)。如果它调用了一个实际的单独的 cmovne,它只是使用 cmove 而不是 operator!=

operator!= 内联到字面上零额外成本,并且对任一函数的所有调用都使用相同的独立定义,从而节省了代码占用空间。有利于性能,尤其是当您的代码同时使用这两种运算符时,足以使其在缓存中保持热状态。

当然,当类只是一个 operator== 时,让 int 内联也会显着节省;根本不调用通常要好得多,因为不需要在某些东西周围保留寄存器。

(当然,在这种情况下,我的示例太简单了:如果它们 相等,那么它仍然可以返回 a.val,因为它知道这与 b.val 相同。因此,如果您取消注释 Godbolt 链接中的 operator== 定义,foo 将编译为 mov eax,DWORD PTR [rdi] / ret,甚至不会触及 b。)

,

您对 inline 关键字的作用有误解。如需说明,请参阅此答案 https://stackoverflow.com/a/66379889/15284149

回答你的问题,是的,“内联”可能更快,这就是为什么编译器实际上会自动优化它(只要你至少有 -O1):https://godbolt.org/z/9Kn3hE

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res