_.isFunction(a) vs. typeof a === 'function'? javascript

前端 未结 2 1879
失恋的感觉
失恋的感觉 2020-12-14 05:54

I think it might be only performance case - http://jsperf.com/comparing-underscore-js-isfunction-with-typeof-function/2

And seems that typeof is faster.

2条回答
  •  旧时难觅i
    2020-12-14 06:00

    Firstly, Underscore doesn't use that implementation anymore. It optimizes to typeof unless typeof /./ returns function, as it did atleast in older versions of Chrome

    You can find this in the source code: http://underscorejs.org/underscore.js

    // Optimize `isFunction` if appropriate.
      if (typeof (/./) !== 'function') {
        _.isFunction = function(obj) {
          return typeof obj === 'function';
        };
      }
    

    New jsperf: http://jsperf.com/comparing-underscore-js-isfunction-with-typeof-function/3

    It still shows quite a performance hit in FF (but MUCH less than the naive implementation you posted in the question), which is due to the overhead of a function call vs just inlining code.

提交回复
热议问题