Abazine Abdellatif
Abazine Abdellatif

Reputation: 61

which way to swap two variable values is more optimised?

The methods are about swapping of two variables in javaScript.

Method 1:

var a=0,b=1,c=a;

a = b;

b = c;

Method 2:

var [a,b] = [0,1];

[a,b] = [b,a];

Upvotes: 2

Views: 482

Answers (1)

holydragon
holydragon

Reputation: 6728

Here you can see by yourself.

Change the NUMBER_OF_TIMES as you would like.

Also run it as many times as you want to get the average.

let NUMBER_OF_TIMES = 1000000
console.time("Method1")
for (let i = 0; i < NUMBER_OF_TIMES; i++) {
  var a = 0, b = 1, c = a;
  a = b;
  b = c;
}
console.timeEnd("Method1")
console.time("Method2")
for (let i = 0; i < NUMBER_OF_TIMES; i++) {
  var [a, b] = [0, 1];
  [a, b] = [b, a];
}
console.timeEnd("Method2")

Upvotes: 3

Related Questions