首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么重新分配函数指针会减慢函数调用的速度

为什么重新分配函数指针会减慢函数调用的速度
EN

Stack Overflow用户
提问于 2019-05-30 23:34:28
回答 2查看 51关注 0票数 2

我的问题是,如果我在已经为p分配了一个函数之后,将它指向另一个函数,则调用它的性能会显著降低。

代码语言:javascript
运行
复制
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,然后设置为不同的函数会改变性能?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56381296

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档