<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
var array_list = [];
for (var i = 0; i < 1000; i++) {
array_list[i] = i;
}
array_list.indexOf(0);
jQuery.inArray(0, array_list);
array_list.indexOf(999);
jQuery.inArray(999, array_list);
array_list.indexOf(499);
jQuery.inArray(499, array_list);
array_list.indexOf(0);
array_list.indexOf(499);
array_list.indexOf(999);
jQuery.inArray(0, array_list);
jQuery.inArray(499, array_list);
jQuery.inArray(999, array_list);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
indexOf first | |
$.inArray first | |
indexOf last | |
$.inArray last | |
indexOf middle | |
$.inArray middle | |
indexOf | |
$.inArray |
Test name | Executions per second |
---|---|
indexOf first | 85075440.0 Ops/sec |
$.inArray first | 47956812.0 Ops/sec |
indexOf last | 7339743.0 Ops/sec |
$.inArray last | 6826294.5 Ops/sec |
indexOf middle | 13104139.0 Ops/sec |
$.inArray middle | 11709690.0 Ops/sec |
indexOf | 4801297.0 Ops/sec |
$.inArray | 4343027.0 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Overview
The provided JSON represents a JavaScript microbenchmark that compares the performance of indexOf
(a native JavaScript method) and $inArray
(a jQuery utility function). The benchmark consists of 8 test cases, each measuring the execution time of the two methods for different input values: the first element in the array (0
), the last element in the array (999
), a middle value (499
), and a combination of three consecutive elements.
What is tested?
The benchmark tests the performance of indexOf
and $inArray
on an array of integers. Specifically, it measures:
indexOf
for different input values.$inArray
for different input values.Options compared
The benchmark compares two options:
indexOf
: a built-in method that searches for an element in the array using binary search.$inArray
: a utility function that searches for an element in the array.Pros and Cons of each approach:
indexOf
:$inArray
:indexOf
.Library used
The benchmark uses jQuery version 1.12.4, which was a popular version at the time of its release in 2015. $inArray
is a utility function provided by jQuery that simplifies the process of finding an element in an array.
Special JS feature or syntax
None of the test cases use any special JavaScript features or syntax beyond what's required for the benchmark itself (e.g., let
, const
, arrow functions, etc.).
Other alternatives
If you're looking for alternative methods to implement $inArray
-like behavior in your code, consider:
indexOf
, as shown above.findIndex
.for
loops).The benchmark's results provide insights into the relative performance of indexOf
and $inArray
, which can inform your decision when choosing between these methods in different contexts.