function randomIntFromInterval(min, max) {
// min and max included
return Math.floor(Math.random() * (max - min + 1) + min);
}
var rows = [];
let lasth = 0;
for (let i = 0; i < 10000; i++) {
lasth += randomIntFromInterval(16, 50);
rows.push(lasth);
}
function sliceRange(arr, min, max) {
var l = 0,
r = arr.length;
while (l < r) {
var m = ~~(l + (r - l) / 2);
if (arr[m] < min) l = m + 1;
else if (arr[m] > max) r = m;
else break;
}
var lr = m,
rl = m;
while (l < lr) {
m = ~~(l + (lr - l) / 2);
if (arr[m] < min) l = m + 1;
else lr = m;
}
while (rl < r) {
m = ~~(rl + (r - rl) / 2);
if (arr[m] > max) r = m;
else rl = m + 1;
}
return [l-1, r+1];
}
sliceRange(rows, 70000, 70400)
rows.findIndex( x => x > 70000)-1
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
sliceRange | |
findIndex |
Test name | Executions per second |
---|---|
sliceRange | 3673479.2 Ops/sec |
findIndex | 405806.1 Ops/sec |
Benchmark Overview
The provided JSON represents two test cases for measuring the performance of JavaScript in finding an index range within an array.
First Test Case: sliceRange
The first test case, "sliceRange", is designed to measure the performance of the sliceRange
function, which takes an array and returns the indices of the subarray that falls within a specified range. The array is generated with 10,000 elements, each incremented by a random value between 16 and 50.
Comparison Options
The sliceRange
function uses three approaches to find the index range:
Pros and Cons
Second Test Case: findIndex
The second test case, "findIndex", is designed to measure the performance of the findIndex
function, which returns the index of the first element in an array that satisfies a given condition.
Comparison Options
In this test case, the same three approaches are used as in the first test case: Binary Search (left), Binary Search (right), and Linear Search.
Pros and Cons
The pros and cons for each approach are similar to those mentioned earlier.
Library and Special JS Features
Neither of these test cases uses any libraries or special JavaScript features. The sliceRange
function is a custom implementation, while the findIndex
function is part of the JavaScript standard library.
Alternatives
Other alternatives for finding an index range within an array include:
findIndex
function and other utility functions for working with arrays.In terms of programming languages, alternatives for finding an index range within an array include:
bisect
module can be used to find the insertion point for a given value in a sorted list.Arrays.binarySearch
method can be used to find the index of a given element in a sorted array.std::lower_bound
and std::upper_bound
functions from the <algorithm>
library can be used to find the indices of a given range within an array.