猿问

使用临时变量或不带临时变量交换号码的性能差异

在互联网的深处,我发现了以下帖子:


在不使用新变量的情况下交换两个数字始终是一个好方法。这有助于您的应用程序以内存和性能为导向。


并建议使用以下代码:


int firstNum = 10;

int secondNum = 20;


firstNum = firstNum + secondNum;

secondNum = firstNum - secondNum;

firstNum = firstNum - secondNum;

而不是使用临时变量。


老实说,这对我来说听起来像是一群笨蛋。我知道,在现实环境中,这样的微弱几乎不会有任何区别,但让我感兴趣的是,在这种情况下,避免使用新变量会有什么不同吗?


智慧大石
浏览 90回答 3
3回答

一只斗牛犬

这是一堆巴洛尼;这样的提示仅在早期计算机上具有任何价值(具有严重的寄存器限制)。在现代计算机上,这不是问题。使用临时变量(首选可读性更强的代码)。

慕标琳琳

这不仅是一个可怕的想法,它甚至不是一个可怕想法的良好实现!老把戏是:a^=b;b^=a;a^=b;那个不会有不足/溢出的问题,并且真的会让你的同事更加困惑。我的意思是,如果你要去混乱,表现不佳的代码...一路走来!顺便说一句,我通常会说,如果你认为你可能会从以稍微不那么明显的方式做某事中获得一些性能优势,那就永远不要这样做。首先,你可能错了,你的解决方案并不快。其次,Java已经非常快了,这可能并不重要。第三,随着时间的推移,java将改进“明显”的方式,并使用运行时编译器使它们更快。它不会改善你的黑客攻击,甚至可能使它变慢。如果你不相信我,你可能仍然相信每次连接两个字符串时都应该使用stringbuilder......

慕少森

public class SwapTest {&nbsp; &nbsp; int firstNum = 10;&nbsp; &nbsp; int secondNum = 20;&nbsp; &nbsp; public static void main(String args[])&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; SwapTest swap2Numbers = new SwapTest();&nbsp; &nbsp; &nbsp; &nbsp; long before = System.currentTimeMillis();&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < 1000000; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; swap2Numbers.proceedNoInterimVariable();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(" no temp variable took " + (System.currentTimeMillis()-before));&nbsp; &nbsp; &nbsp; &nbsp; before = System.currentTimeMillis();&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < 1000000; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; swap2Numbers.proceedWithInterimVariable();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("with temp variable took " + (System.currentTimeMillis()-before));&nbsp; &nbsp; }&nbsp; &nbsp; private void proceedNoInterimVariable()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; firstNum = firstNum + secondNum;&nbsp; &nbsp; &nbsp; &nbsp; secondNum = firstNum - secondNum;&nbsp; &nbsp; &nbsp; &nbsp; firstNum = firstNum - secondNum;&nbsp; &nbsp; }&nbsp; &nbsp; private void proceedWithInterimVariable()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; int temp = firstNum;&nbsp; &nbsp; &nbsp; &nbsp; firstNum = secondNum;&nbsp; &nbsp; &nbsp; &nbsp; secondNum = temp;&nbsp; &nbsp; }}从我的系统上,临时变量版本的性能要快得多。&nbsp;no temp variable took 11&nbsp;with temp variable took 4
随时随地看视频慕课网APP

相关分类

Java
我要回答