var o = {'ff1234567890121':0, 'ff1234567890122':1, 'ff1234567890123':2, 'ff1234567890124':3, 'ff1234567890125':4};
var a = ['ff1234567890121', 'ff1234567890122', 'ff1234567890123', 'ff1234567890124', 'ff1234567890125'];
var s = '-ff1234567890121--ff1234567890122--ff1234567890123--ff1234567890124--ff1234567890125-';
var t = 'ff1234567890124';
var i = a.indexOf(t);
var i = s.indexOf('-' + t + '-');
var i = o[t];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array indexOf | |
String indexOf | |
Object lookup |
Test name | Executions per second |
---|---|
Array indexOf | 78815256.0 Ops/sec |
String indexOf | 156970352.0 Ops/sec |
Object lookup | 149132320.0 Ops/sec |
Let's break down what's being tested in this benchmark.
Benchmark Goal The goal of this benchmark is to compare the performance of three different methods for finding the index of a value within an array or string:
Array.indexOf()
String.indexOf()
Object.lookup
(which is actually just using bracket notation, e.g., o[t]
, but we'll discuss this later)Options Compared
Array.indexOf()
:String.indexOf()
: Array.indexOf()
on strings.Object.lookup
(bracket notation):Library/Functionality
Array.indexOf()
: A built-in function in JavaScript's Array prototype.String.indexOf()
: A built-in function in JavaScript's String prototype.Object.lookup
(bracket notation): Not a traditional library, but rather an optimization technique that leverages the way objects store and retrieve property values.Special JS Feature/Syntax
None mentioned explicitly. However, Object.lookup
relies on the fact that objects in JavaScript can be accessed using bracket notation (o[t]
), which is a shorthand for o.hasOwnProperty(t) ? o[t] : undefined
. This syntax is widely supported but not unique to modern JavaScript versions.
Benchmark Considerations
The benchmark measures execution time per second for each of the three methods. The test data consists of an array and string containing a single value that's then searched for within those collections.
Alternative Approaches
Other optimization techniques or approaches could be explored, such as:
Array.prototype.reduce()
to find the indexHowever, these alternatives are not directly related to the specific methods being compared in this benchmark.
Additional Insights
Keep in mind that Object.lookup
(bracket notation) is actually just a clever way of writing o[t]
. It's a performance optimization technique that takes advantage of how objects store property values. This approach can be faster than using the traditional hasOwnProperty()
method or accessing properties directly.
In conclusion, this benchmark provides a useful comparison of three common methods for finding indices within arrays and strings, highlighting their relative performance characteristics.