什么更快?运行空函数或检查函数是否未定义

What is faster? Running an empty function or checking if function is undefined?

本文关键字:函数 检查 是否 未定义 运行 什么      更新时间:2023-09-26

我正在编写一些代码,其中作为参数传入的函数有时可能未定义。出于对这种不良"做法"的好奇,我想知道实际上什么更快?给出一个空函数,或者让函数检查参数是否未定义?

我做了以下测试来尝试。答案非常令人惊讶!

var timesTest = 1000;
function empty(){}
console.time('running an empty function');
for( var i=0; i<timesTest; i++ ){
  empty();
}
console.timeEnd('running an empty function');
var somethingthatdoesnotexist;
console.time('checking if a function exists');
for( var i=0; i<timesTest; i++ ){
  if( somethingthatdoesnotexist ){
    somethingthatdoesnotexist();
  }
}
console.timeEnd('checking if a function exists');
// results:
// running an empty function: 0.103ms
// checking if a function exists: 0.036ms

在低数字下,检查未定义的参数要快得多。

一旦测试时间增加,事情就会变得有趣。

// var timesTest = 100000;
// results:
// running an empty function: 1.125ms
// checking if a function exists: 1.276ms 

// results:
// var timesTest = 1000000000;
// running an empty function: 2096.941ms
// checking if a function exists: 2452.922ms 

随着测试数量的增加,运行空白函数的速度会快一些。

我还没有尝试在图表上绘制这个,但我对这种行为很好奇。有谁知道这是为什么?这对现实世界代码中的事物有何影响?

  1. http://jsperf.com 更准确的基准测试和花哨的图表。我做了一个:http://jsperf.com/empty-vs-check

  2. 这是微优化。没有人会注意到差异。十亿次迭代的差异不到半秒,这永远不会发生。做你认为更具可读性的事情;不用担心性能。