var sampleString = 'abcdefghijklmnopqrstuvwxyz';
var recurseFindIndex = (charArray, i = 0) => {
const [curr, rest] = charArray;
if (curr === 'z') return i;
else return recurseFindIndex(rest, i + 1);
};
sampleString.split('').findIndex(char => char === 'z');
recurseFindIndex(sampleString);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
findIndex | |
Recursion |
Test name | Executions per second |
---|---|
findIndex | 2777001.5 Ops/sec |
Recursion | 163935.2 Ops/sec |
Let's break down the benchmark test.
Benchmark Definition
The benchmark is designed to compare two approaches for finding the index of a character within a string:
split('').findIndex(char => char === 'z')
: This approach uses the split
method to convert the string into an array of characters, and then calls the findIndex
method on that array. The callback function passed to findIndex
checks if each character is equal to 'z'
.recurseFindIndex(sampleString)
: This approach is a custom recursive function defined in the JavaScript code. It iterates through the string character by character, checking if the current character is equal to 'z'
. If it finds a match, it returns the index; otherwise, it recursively calls itself on the remaining characters.Options Compared
The two approaches are compared, with the first one being the built-in split
and findIndex
method, and the second one being the custom recursive function. The test is likely trying to determine which approach is faster for finding a specific character within a string.
Pros and Cons of Each Approach
split
and findIndex
method:recurseFindIndex
):Library/Functionality Used
The split
method is a standard JavaScript method that converts a string into an array of elements. The findIndex
method is also a standard JavaScript method that returns the index of the first element in the array that satisfies the provided condition.
Special JS Feature/Syntax
There doesn't appear to be any special JavaScript features or syntax used in this benchmark.
Other Alternatives
If you wanted to test alternative approaches, some possible options could include:
indexOf
instead of findIndex
, which would iterate through the string until finding a match and then return the index.split
or findIndex
.Keep in mind that these alternatives might not be suitable for this specific benchmark, which is focused on comparing two simple approaches with built-in JavaScript methods.