在函数创建过程中变量实例化的以下策略(解构与主体的一部分)之间的变量之间是否存在任何差异:
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);
据我所知,这两种方法都会创建两个变量,但我想知道哪种方法在速度和内存方面更好。
最佳答案
无法确定在最短时间内完成的方法。 stacksnippets 和 console
调用似乎也会影响结果。
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");
关于javascript - 函数体的解结构变量和变量部分之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41540405/