我的问题是,如果我在已经为p
分配了一个函数之后,将它指向另一个函数,则调用它的性能会显著降低。
function func1() {} // two identical empty functions
function func2() {} // different in name only
var p = func1; // default to func1
var count = 0; // current loop
var elapse = 0; // elapsed time for 1,000,000 calls on each loop
var start = 0; // start time for 1,000,000 calls on each loop
var total = 0; // total elapsed time for all loops
function loop() {
start = performance.now(); // get start time
for (let i = 0; i < 1000000; i ++) if (p !== undefined) p(); // do 1,000,000 calls or early out 1,000,000 times if undefined
elapse = performance.now() - start;
total += elapse; // used for getting average
count ++;
console.log(p + "\nelapsed " + elapse + "\naverage " + total / count);
// Switch between the lines below to see the performance difference.
p = (p === func1) ? p = undefined : p = func1; // best performance
//p = (p === func1) ? p = func1 : p = func1; // good performance
//p = (p === func1) ? p = func2 : p = func1; // bad performance
// pattern: func1 -> undefined -> func2 -> undefined -> repeat
/*if (p === undefined) p = (count % 4 === 0) ? p = func1 : p = func2;
else p = undefined;*/ // also bad performance
if (count < 500) loop(); // start the next loop
}
console.clear();
loop(); // start the loop
此外,为什么将p
设置为undefined
并返回到原始函数不会改变性能,而将p
设置为undefined
,然后设置为不同的函数会改变性能?
https://stackoverflow.com/questions/56381296
复制相似问题