Which way to change variables is more optimized?

2

I made two ways to change the value a and b , but which is more optimized, taking this example to other languages like desktop or web.

Without using auxiliary variable:

$a = 10;
$b = 5;

$a = $b+$a;
$b = $a-$b;
$a -= $b;

Using auxiliary variable:

$a = 10;
$b = 5;

$c = $a;
$a = $b;
$b = $c;
    
asked by anonymous 19.08.2017 / 21:31

2 answers

3

First, it's PHP, right? So it does not matter, the language was not designed to perform operations that need extreme optimization.

The comparison comes to be unfair since the second code is making 3 simple assignments, the first is doing this and still 3 more arithmetic operations, so it is easy to see that the second is faster. But the difference will be ridiculous. I would only opt for the second because it is also simpler.

    
19.08.2017 / 21:35
1

The asymptotic complexity of both forms is equal, that is, for large volumes of operations, the difference between them is negligible.

Now, if you really want to measure and compare the runtime of both, in Java you can use the System.currentTimeMillis() method before and after execution and compare the difference.

    
21.08.2017 / 16:49