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;
rough: {
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 rough;
}
return [];
}
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 | 3642168.2 Ops/sec |
findIndex | 603074.7 Ops/sec |
Measuring performance is an essential aspect of software development, and JavaScript is no exception.
Let's break down the provided benchmark definitions:
Benchmark Definition JSON
The first part represents a benchmark definition for a custom function sliceRange
. It defines:
rows
with random elements.sliceRange
function takes an array arr
, and two integers min
and max
as input, and returns the range of indices where all elements are within [min, max]
.The second part represents individual test cases:
findIndex
method with a callback function that checks if an element is greater than 70,000.findIndex
, but directly using the -1
index offset.Options compared
Two different approaches are being tested:
sliceRange
function uses two while loops to perform a manual binary search for the desired range. This approach has a time complexity of O(log n), where n is the length of the array.findIndex
method: Both test cases use the findIndex
method, which searches for the first element that satisfies the provided callback function. The findIndex
method also uses a binary search algorithm internally.Pros and Cons
Manual binary search (sliceRange)
Pros:
Cons:
Built-in findIndex
method
Pros:
Cons:
Library usage
The sliceRange
function uses a custom implementation, while the findIndex
method is a built-in JavaScript method. The findIndex
method is part of the ECMAScript standard and is widely supported across different browsers and environments.
Special JS feature or syntax
No special JavaScript features or syntax are used in this benchmark definition.
Alternatives
If you need to measure performance for other similar use cases, consider using a library like:
bustache
: A high-performance templating engine that provides a range of optimization techniques.lodash
(specifically the findIndex
method): A popular utility library with an efficient implementation of the findIndex
method.Keep in mind that the choice of alternative libraries depends on your specific use case and requirements.