Performance difference of swapping numbers with temporary variable or without

Krzysztof Atłasik :

In the depths of the Internet I found the following post:

Swapping two numbers without using a new variable is always a good approach. This helps your application to be memory and performance oriented.

And it proposes to use the following code:

int firstNum = 10;
int secondNum = 20;

firstNum = firstNum + secondNum;
secondNum = firstNum - secondNum;
firstNum = firstNum - secondNum;

instead of using a temporary variable.

To be honest it sounds for me like a bunch of baloney. I know, that in a real environment such microtweaks wouldn't do almost any difference, but what intrigues me is, if avoiding using a new variable, in this case, would do any difference?

user738048 :
public class SwapTest {

    int firstNum = 10;
    int secondNum = 20;

    public static void main(String args[])
    {
        SwapTest swap2Numbers = new SwapTest();
        long before = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            swap2Numbers.proceedNoInterimVariable();
        }
        System.out.println(" no temp variable took " + (System.currentTimeMillis()-before));

        before = System.currentTimeMillis();
        for (int i = 0; i < 1000000; i++) {
            swap2Numbers.proceedWithInterimVariable();
        }
        System.out.println("with temp variable took " + (System.currentTimeMillis()-before));
    }

    private void proceedNoInterimVariable()
    {

        firstNum = firstNum + secondNum;
        secondNum = firstNum - secondNum;
        firstNum = firstNum - secondNum;
    }

    private void proceedWithInterimVariable()
    {
        int temp = firstNum;
        firstNum = secondNum;
        secondNum = temp;
    }

}

From this on my system the temp variable version performs much faster.

 no temp variable took 11
 with temp variable took 4

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=309514&siteId=1