var arrayHandlers = [];
var objectHandlers = {};
var handlersCount = 100;
var functionHandlersToFind = [];
var hashesToFind = [];
var generateHash = function(ix) {
return 'hdl' + ix;
}
var createHandler = function() {
return function(data) {
return "#Count:" + data;
}
};
for (let i = 0; i < handlersCount; i++) {
let theNewHandler = createHandler();
arrayHandlers.push(theNewHandler);
functionHandlersToFind.push(theNewHandler);
let generatedHash = generateHash(i);
objectHandlers[generatedHash] = theNewHandler;
hashesToFind.push(generatedHash);
}
functionHandlersToFind.forEach((fnHandler) => arrayHandlers.find(handler => handler === fnHandler))
hashesToFind.forEach((hash, ix) => objectHandlers[hash])
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Find from array using function reference | |
Find by object keys |
Test name | Executions per second |
---|---|
Find from array using function reference | 189398.4 Ops/sec |
Find by object keys | 1593479.2 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Overview
The benchmark tests two different approaches to access elements in an array: using a function reference (i.e., arrayHandlers.find(handler => handler === fnHandler)
) and using object keys (i.e., hashesToFind.forEach((hash, ix) => objectHandlers[hash])
).
Options Compared
Two options are compared:
find()
method to search for an element in the arrayHandlers
array based on a function reference.objectHandlers
object to access elements based on their associated keys.Pros and Cons of Each Approach
Library Used
The benchmark uses the Array.prototype.find()
method and the Object
data structure, which are built-in JavaScript features. No external libraries are required.
Special JS Feature or Syntax
This benchmark uses the following special JavaScript feature:
(fnHandler) => arrayHandlers.find(handler => handler === fnHandler)
and (hash, ix) => objectHandlers[hash]
), which were introduced in ECMAScript 2015 (ES6).Other Considerations
When choosing between these two approaches, consider the following factors:
Alternative Approaches
Other alternatives to consider:
indexOf()
instead of find()
: This can provide better performance for finding a specific element in an array since it doesn't require creating a new function reference.Keep in mind that the best approach depends on your specific use case and performance requirements.