var matches = ['alpha', 'beta', 'charlie', 'delta'];
var regex = new RegExp(`(${matches.join('|')})$`);
var str = 'abcdefghijklmnopqrstuvwxyz';
matches.some(match => str.endsWith(match))
regex.test(str)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
endsWith | |
regex |
Test name | Executions per second |
---|---|
endsWith | 2493544.5 Ops/sec |
regex | 5448965.5 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and what are the pros and cons of each approach.
Benchmark Overview
The benchmark measures the performance difference between using String.prototype.endsWith()
method versus regular expression (RegExp
) to check if a string ends with one or more specific substrings. The test case uses an array of strings ['alpha', 'beta', 'charlie', 'delta']
and concatenates them into a regex pattern.
Script Preparation Code
var matches = ['alpha', 'beta', 'charlie', 'delta'];
var regex = new RegExp(`(${matches.join('|')})$`);
var str = 'abcdefghijklmnopqrstuvwxyz';
This code creates:
matches
regex
) that matches any string in matches
at the end of a target stringstr
Html Preparation Code
The benchmark doesn't require any HTML preparation code, which means it only tests the JavaScript execution and doesn't involve rendering or layout calculations.
Test Cases
There are two individual test cases:
String.prototype.endsWith()
method to check if str
ends with one of the strings in matches
.matches
at the end of str
.Pros and Cons
Here's a brief analysis of each approach:
matches
at the end of str
Library (regex)
The regular expression library is built into most JavaScript engines, including modern browsers like Chrome. The RegExp
constructor creates a new regex object that can be used for pattern matching.
Special JS Feature (none)
This benchmark doesn't use any special JavaScript features or syntax beyond the standard language.
Other Alternatives
If you're interested in exploring other approaches:
Keep in mind that these alternatives are not necessary for running the provided benchmark and may add additional complexity to your project.