-1
var x=10;
var y=5;

Solution 1

x= x + y 
y= x - y 
x= x - y 

Solution 2

x=y+x,y=x-y,x=x-y;

the two solutions are equal to each other but the second one is faster, why?

Can anyone show me the optimized opcode generated for both solutions by JS engine?

nullException
  • 1,112
  • 4
  • 17
  • 29
  • 1
    Solution 1 & Solution 2 is same code. – Człowiek Fin Śpiewak Nov 20 '14 at 17:34
  • Watch out if you are expecting integer arithmetic and x and y are of v.large magnitude - since x + y could exceed the integer range. – GavinBrelstaff Nov 20 '14 at 17:35
  • Apart from that, speed might depend on using the += and -= operators (it used to in C) x += y; y = x - y; x -= y; – GavinBrelstaff Nov 20 '14 at 17:37
  • 1
    As expected, the assertion that one is faster is simply wrong: http://jsperf.com/two-ways-of-swapping – T.J. Crowder Nov 20 '14 at 17:41
  • No, this isn't a duplicate of http://stackoverflow.com/questions/16201656/how-to-swap-two-variables-in-javascript. Actually **read** the question above, it's about optimization and why would is faster than the other. (It's wrong, but not a duplicate.) – T.J. Crowder Nov 20 '14 at 17:42
  • This question appears to be off-topic because it is based on a mistaken assumption. – T.J. Crowder Nov 20 '14 at 17:43
  • you are right.. same speed, and this is the generated opCode movl $10, -4(%rbp) movl -4(%rbp), %eax addl %eax, -8(%rbp) movl -4(%rbp), %eax movl -8(%rbp), %edx subl %eax, %edx movl %edx, %eax movl %eax, -4(%rbp) movl -4(%rbp), %eax subl %eax, -8(%rbp) movl $0, %eax – nullException Nov 20 '14 at 17:47
  • @nullException: Well, that's what it is with one specific JavaScript compiler. There are several different ones. – T.J. Crowder Nov 20 '14 at 17:48

2 Answers2

0

Well, in Ecmascript 6 you can do:

var x=10;
var y=5;

[x,y] = [y,x]
console.log(x,y) // 5, 10

If not, here is already a good way: How to swap two variables in JavaScript

As for the 2 methods you have, doubt they are different, you should first try to check whether there is a big time difference with multiple tests

Community
  • 1
  • 1
juvian
  • 15,875
  • 2
  • 37
  • 38
0

I can't find any meaningful difference in performance for either solution or using XOR. Non on the test are consistently faster so I assume the premise of the question is incorrect.

JSLitmus.test('Solution1', function() {
    var x = 10;
    var y = 5;    
    x = x + y;
    y = x - y;
    x = x - y;
});

JSLitmus.test('Solution2', function() {
    var x = 10;
    var y = 5;
    x = y + x, y = x - y, x = x - y;
});

JSLitmus.test('Solution3', function() {
    var x = 10;
    var y = 5;
    x ^= y;
    y ^= x;
    x ^= y;
});

http://jsfiddle.net/6L0d6rpn/

Sam Greenhalgh
  • 5,952
  • 21
  • 37