Which way to change variables is more optimized?

Asked

Viewed 44 times

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.

No use 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;

2 answers

3


First, it’s PHP, right? So it doesn’t matter, the language wasn’t created to perform operations that need extreme optimization.

The comparison is even unfair since the second code is making 3 simple assignments, the first one is doing this and 3 more arithmetic operations, so it is easy to notice that the second one is faster. But the difference will be derisory. I would only choose the second because it is also simpler.

  • Passing this same code to Java or C#, etc, would it be possible to measure precisely the difference between them ? For example, the space used in memory, or processing used.

  • There’s always a measure.

  • But it can complement your answer with how to measure ??

  • There are many forms, you are still adding other languages, each one has its own way. When you ask a question you have to decide what you want to know first. The general way is to have it done and take the execution time. I have an answer on this: https://answall.com/q/89622/101

  • Perhaps, the memory allocation request compensates for the time of arithmetic operations, usually asking the OS for resources is quite slow, don’t you think?

  • You’re not gonna ask the operating system for anything. If it is PHP, the memory is managed and does not keep asking for every necessary allocation and even if it asked to allocate accurate operating system, assign does not need. In this case, as it is in the answer. is allocating and assigning the same number of times in both cases, the only difference is that one does arithmetic operations and the other does not.

Show 1 more comment

1

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.