简体   繁体   中英

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

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.

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.zy; 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.zy; 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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM