难道换不使用第三个提高性能的两个变量? [英] Does swapping two variables without using a third improve performance?

查看:173
本文介绍了难道换不使用第三个提高性能的两个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了很多的技术来交换两个变量不使用第三。

I've seen a lot of techniques for swapping two variables without using a third.

<一个href="http://stackoverflow.com/questions/804706/swap-two-variables-without-using-a-temp-variable">Swap两个变量不使用临时变量
<一href="http://stackoverflow.com/questions/23514846/how-to-swap-two-numbers-without-using-third-variable">How交换两个号码,而无需使用第三个变量? [复制]
<一href="http://stackoverflow.com/questions/24844487/swap-2-values-of-2-variables-without-using-a-third-variable-python">Swap 2值的2个变量,而无需使用一个第三可变;蟒蛇
<一href="http://stackoverflow.com/questions/18356437/swap-two-variables-value-without-using-third-variable-in-php">Swap没有在PHP中使用第三个变量两个变量值[复制]
<一href="http://stackoverflow.com/questions/3647331/how-to-swap-two-numbers-without-using-temp-variables-or-arithmetic-operations">How交换两个号码,而无需使用临时变量或算术运算?

Swap two variables without using a temp variable
How to swap two numbers without using third variable? [duplicate]
Swap 2 values of 2 variables without using a third variable; python
Swap two variables value without using third variable in php [duplicate]
How to swap two numbers without using temp variables or arithmetic operations?

是任何一种比使用第三个变量更快?

Are any of these faster than using the third variable?

推荐答案

没有,即使在看电脑金佳宾点。

no even in computer archtecture point of view.

例如,如果我使用的位操作交换两个整数类似以下内容:

for example, if i use bit manipulation to swap two integer like following:

a ^= b;
b ^= a;
a ^= b;

什么运行的CPU是:

what running in CPU is that:

mov reg1, &a
mov reg2, &b
xor reg1, reg2
xor reg2, reg1
xor reg1, reg2

有什么可以很容易分辨的是,REG1和REG2互相依靠。

what can tell easily is that reg1 and reg2 rely on each other.

现代的CPU使用障碍的执行指令流。也就是说,执行多个指令,如果这些指令不互相依赖的结果。因此,这是正常的现代的CPU在同一时刻运行多个指令。

modern CPUs use disorder execution of instruction stream. that is, execute more than one instructions if these instructions do not rely on the result of each other. therefore, it's normal for modern CPUs run multiple instructions at the same moment.

但如果你使用一个临时变量? 死很容易。现代CPU通常有指令级的支持。

but what if you use a temp variable? dead easy. modern CPUs usually have instruction level support.

xchg reg1, reg2

完成的。

顺便说一句,不要过多地关注到装配。它在不同的体系结构而异。只是为了演示。

BTW, don't pay too much attention to the assembly. it varies in different architectures. just for demo.

这篇关于难道换不使用第三个提高性能的两个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆