Difference between de-structured variables and variables part of a function body

62 views Asked by At

Is there any differences between the variables during the following strategies (de-structured versus part of body) of variable instantiation during function creation:

let obj = {z: {y: 99}}
let foo = ({z: {y}, x = `${y+1}`}) => console.log(x) //prints 100
let bar = (data) => {
    let y = data.z.y;
    let x = `${y+1}`;
    console.log(x);  //also prints 100
}
foo(obj);
bar(obj);

As far as I know both of these will create two variables, but I am wondering which is the superior approach in way of speed and memory.

1

There are 1 answers

0
guest271314 On

Could not definitively conclude approach which completes in least amount of time. stacksnippets and console calls also appear to influence results.

let obj = {
  z: {
    y: 99
  }
};
console.profile("foo");
let foo = ({z: {y},x = `${y+1}`}) => console.log() //prints 100
foo(obj);
console.profileEnd("foo");

console.profile("bar");
let bar = (data) => {
  let y = data.z.y;
  let x = `${y+1}`;
  console.log(); //also prints 100
}

bar(obj);
console.profileEnd("bar");

let res = {
  foo:null,
  bar:null
}

res.foo = new Date().getTime();
console.time("foo");
for (let i = 0; i < 100; i++) {

  foo(obj);

}
console.timeEnd("foo");
res.foo = new Date().getTime() - res.foo;

res.bar = new Date().getTime();
console.time("bar");
for (let i = 0; i < 100; i++) {

  bar(obj);

}
console.timeEnd("bar");
res.bar = new Date().getTime() - res.bar;

console.log(JSON.stringify(res, null, 2));

let obj = {
  z: {
    y: 99
  }
};
console.profile("foo");
let foo = ({z: {y},x = `${y+1}`}) => x; //prints 100
foo(obj);
console.profileEnd("foo");
console.profile("bar");
let bar = (data) => {let y = data.z.y;
  let x = `${y+1}`;
  return x; //also prints 100
}

bar(obj);
console.profileEnd("bar");

console.time("foo");
for (let i = 0; i < 100; i++) {

  foo(obj);

}
console.timeEnd("foo");

console.time("bar");
for (let i = 0; i < 100; i++) {

  bar(obj);

}
console.timeEnd("bar");