var string = '{{ vars.test }}';
var startDelim = '{{';
var endDelim = '}}';
var matcher = new RegExp(`${startDelim}((?!${endDelim}).+?)${endDelim}`, 'g');
string.includes(startDelim) && string.includes(endDelim);
string.matchAll(matcher);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
String.includes() | |
String.matchAll() |
Test name | Executions per second |
---|---|
String.includes() | 3763542.0 Ops/sec |
String.matchAll() | 3891718.0 Ops/sec |
Let's break down the benchmark and explain what's being tested, compared, and discussed.
Benchmark Goal
The goal of this benchmark is to compare the performance of two JavaScript methods: string.includes()
and string.matchAll()
. The test aims to determine which method is faster for searching a specific pattern within a string.
Script Preparation Code The script preparation code defines some variables:
string
: a variable that will hold the input string, initialized with a placeholder value ({{ vars.test }}
).startDelim
and endDelim
: variables that define the start and end delimiters of the pattern to search for. In this case, startDelim
is set to '{{'
and endDelim
is set to "}}"
.The script also defines a regular expression (matcher
) that captures the pattern startDelim + (?!endDelim) .+? endDelim
, which matches any character that is not followed by endDelim
. The (?!...)
part is a negative lookahead assertion, which checks if the current position in the string does not match the pattern before endDelim
.
Comparison Options The two comparison options being tested are:
string.includes(startDelim) && string.includes(endDelim);
: This method uses the includes()
method to search for both startDelim
and endDelim
within the input string.string.matchAll(matcher);
: This method uses the matchAll()
method with a regular expression to find all occurrences of the defined pattern in the input string.Pros and Cons
string.includes(startDelim) && string.includes(endDelim);
:includes()
.string.matchAll(matcher);
:includes()
calls, as it scans the entire string at once.Library and Syntax
The String.prototype.includes()
method is used in the first test case. This method searches for the specified value within a string and returns true
if it exists, or false
otherwise.
There are no special JavaScript features or syntax mentioned in this benchmark.
Alternative Approaches Other approaches to comparing these two methods might include:
string.indexOf(startDelim)
and string.indexOf(endDelim)
instead of includes()
. This would eliminate the repeated calls to includes()
but might not be as efficient as using matchAll()
.Keep in mind that these alternative approaches might affect the performance characteristics of the benchmark, so it's essential to test them thoroughly to determine their relative merits.