Reputation: 2760
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
Reputation: 49744
Quite apart from the fact that the second one can overflow*, there are three possible answers for this:
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
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