<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.core.js"></script>
window.sample = function () {};
window.$isFunction = function (v) { return typeof v === 'function'; };
var isfunc = _.isFunction(sample);
var isfunc = typeof sample === 'function';
var isfunc = sample instanceof Function;
var isfunc = $isFunction(sample);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
isFunction | |
typeof function | |
instanceof | |
wrapped typeof function (like optimized _.isFunction) |
Test name | Executions per second |
---|---|
isFunction | 42723464.0 Ops/sec |
typeof function | 130899288.0 Ops/sec |
instanceof | 105848112.0 Ops/sec |
wrapped typeof function (like optimized _.isFunction) | 131643336.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Definition The benchmark is designed to compare four different approaches for checking if an object or value is a function in JavaScript:
typeof function
isFunction
(a custom implementation)instanceof Function
Options Compared
typeof function
: uses the built-in typeof
operator with the string 'function'
.$isFunction
: a custom implementation of the isFunction
function, which checks if a value is a function using the typeof
operator.instanceof Function
: uses the instanceof
operator to check if an object is an instance of the Function
constructor.Pros and Cons
typeof function
:$isFunction
: similar to typeof function
, but implemented as a custom function.typeof
operator.instanceof Function
:typeof function
, may require more computational resources.Library Used
The benchmark uses Lodash (version 4.17.5) as a dependency. Specifically, it imports the _.isFunction
function from Lodash.
Special JS Feature/Syntax There is no special JavaScript feature or syntax used in this benchmark. The tests only involve basic JavaScript operations and functions.
Other Alternatives
Function.isFunction()
method (introduced in ECMAScript 5) or creating a custom implementation similar to $isFunction
.In summary, this benchmark provides a simple and controlled way to compare different approaches to checking if an object or value is a function in JavaScript, highlighting the trade-offs between using the built-in typeof
operator, a custom implementation like $isFunction
, and the instanceof
operator.