当前位置:网站首页>使用异或交换两个变量是低效的
使用异或交换两个变量是低效的
2022-07-17 00:10:00 【tissar】
异或交换
我们通常会遇到这样的面试题:
- 请编写一个函数,交换 a、b 两个变量,且不能使用额外的临时变量。
通常答案是这样的:
#define SWAP(a,b) do { \ (a) ^= (b); \ (b) ^= (a); \ (a) ^= (b); \ } while(0)
在面试的时候,这个答案或许是满意的。
《Linux 多线程服务端编程:使用 muduo c++ 网络库》的作者陈硕在书中(P501)指出:
- 这个所谓的“技巧”在现代的机器上只会更慢。原始办法是两次内存读和写,这个“技巧”是六读三写加三次异或。
- 同样也不能节省内存,因为中间变量tmp通常会是寄存器。就算它在函数的局部堆栈上,反正栈已经开在那儿了,也没有进一步的函数调用,根本节约不了一丁点内存。
- 相反,由于计算步骤较多,会使用更多的指令,编译后的机器码长度会增加。
C 语言对策
#define SWAP(a,b) do { \ typeof(a) _a = (a); \ typeof(b) _b = (b); \ (void)( &_a == &_b ); \ (a) = _b; \ (b) = _a; \ } while(0)
- 第2行定义变量 _a,第3行同理。
- 第4行,通过比较 _a 和 _b 的地址,检查他们的类型是否相同。如果类型不相同,则会在编译时出现 error 或者 warming。之所以加 (void),也是为了防止编译器 warming。
- 第5、6行实现交换两个变量。
虽然步骤多了,临时变量多了;但是多了类型判断,有得有失。
C++ 语言对策
在 c++ 编程中,交换两个变量就方便的多了。
我们可以使用 STL 的通用工具 swap。它的定义在< utility >中
template <typename T>
inline void swap(T& a, T& b) {
T tmp(std::move(a));
a = std::move(b);
b = std::move(tmp);
}
边栏推荐
- Redis 突然变慢了?
- Classification and use of express Middleware
- 基于移动终端的MIMO阵列三维成像技术
- Today's code farmer girl learned about nodejs and repl interactive interpreter
- 5章 性能平台GodEye源码分析-第三方模块
- VSCode中安装Go:tools failed to install.
- 数字藏品NFT那个平台好
- 每日10道面试题打卡——JVM篇
- NFT differentiation trend has shown, how to capture value?
- Byte two side: what is pseudo sharing? How to avoid it?
猜你喜欢

The popularity of NFT IP licensing is rising, and the era of nft2.0 is coming?

2章 性能平台GodEye源码分析-数据模块

4章 性能平台GodEye源码分析-监控模块

【文献阅读】TENET: A Framework for Modeling Tensor Dataflow Based on Relation-centric Notation

axs火爆,还有哪些打金游戏(上)

基于开源流批一体数据同步引擎ChunJun数据还原—DDL解析模块的实战分享

Punch in 10 interview questions every day - JVM article

binary search

04 BTC implementation

6章 性能平台GodEye源码分析-自定义拓展模块
随机推荐
CheckPoint and DataNode
普通异步发送代码编写
Express project creation and its routing introduction
实时开发平台建设实践,深入释放实时数据价值丨04期直播回顾
基于移动互联网应用的儿童网络保护产业实践与完善
Nmap and Nikto scanning
【文献阅读】Counting Integer Points in Parametric Polytopes Using Barvinok‘s Rational Functions
Common asynchronous sending code writing
CMTime简单介绍
How to use express and how to match and use routes
Xcode11新建项目后的一些问题
3章 性能平台GodEye源码分析-内存模块
Cocos Creator 3.0 基础——事件系统
Laravel之文件上传
The popularity of NFT IP licensing is rising, and the era of nft2.0 is coming?
温州大学X袋鼠云:高等人才教育建设,如何做到“心中有数”
apt-get update报错:Hash 校验和不符
元宇宙会给万亿市场的音乐产业带来哪些变化?
组合键截图分析
Redis+Caffeine两级缓存,让访问速度纵享丝滑