JPS
JPS

Reputation: 2760

Which is better to swap numbers? Using temporary variable or without it? Does it even matter?

I have been asked a question to swap two numbers without using temporary variable. It was a easy to answer the question with the following answer.

swapping with temp variable

int a =10;
int b =20;
int temp = a;
a = b;
b = temp;

swapping without temp variable

int a =10;
int b =20;
a = a+b;
b = a-b;
a = a-b;

It works, But which is better in terms of performance? When it is only one time operation performance doesn't matter i think. But if i need to reverse a huge array of numbers using this swapping method or during a selection sort where swapping needed etc.., creating local variable is better or doing it with arithmetic operation?

Upvotes: 1

Views: 1346

Answers (2)

biziclop
biziclop

Reputation: 49744

Quite apart from the fact that the second one can overflow*, there are three possible answers for this:

  1. You can measure it.
  2. Only think about this level of optimisation if you've measured it and this is really proven to be a problem. (In this instance it is highly unlikely that you'll be able to measure any appreciable difference.)
  3. When in doubt, it's usually a good idea to choose the simpler / more canonical solution. A lot of optimisations are based on the premise that you write "normal" code, and will look for patterns developers usually employ. Naive optimisation efforts can sometimes result in inferior performance with Java Hotspot.

So unless you want to dive into the wonderful and tricky (but fun) world of microbenchmarking, just go with the temp variable.

*Though because of the way Java handles overflows, you'll still get the correct result. But as an aside, if you use xor instead of arithmetic operations, there is no danger of overflow.

P.s.: If you are reversing a huge array, the running time will be overwhelmingly dominated by memory access to the array.

Upvotes: 1

Abhijit Pritam Dutta
Abhijit Pritam Dutta

Reputation: 5591

I will say definitely with a temp variable i.e. your first option. If you refer to your second example you have done total three operation. For each operation your java virtual machine generate equivalent assembly operation. But in your first option with a temp variable you are just swapping the values. Hence very minimal assembly operation only to read from address and write into address.

Upvotes: 2

Related Questions