var result = 0;
FILTERS = /\s*\|\s*([^\|\s:}]*)(?::((?:(?:[^\|\s,}]*),?)+))?\s*/g;
var str = "{{value.foo.bar.baz[2]}}";
for (var i=0; i < 1000; i++) {
typeof str.match(FILTERS) !== null ? result += 1 : result += 0;
}
var result = 0;
FILTERS = /\s*\|\s*([^\|\s:}]*)(?::((?:(?:[^\|\s,}]*),?)+))?\s*/g;
var str = "{{value.foo.bar.baz[2]}}";
for (var i=0; i < 1000; i++) {
typeof str.indexOf('|') >= 0 ? result += 1 : result += 0;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
regex | |
indexOf |
Test name | Executions per second |
---|---|
regex | 1729.0 Ops/sec |
indexOf | 469660.0 Ops/sec |
I'll break down the benchmark and explain what's being tested, compared, pros and cons of different approaches, library usage, special JavaScript features, and alternatives.
Benchmark Overview
The benchmark compares two ways to search for a character in a string: using regular expressions (regex) and the indexOf()
method. The test case uses a specific string with nested properties ({{value.foo.bar.baz[2]}}
) to exercise both the regex and indexOf()
methods.
Regex vs. indexOf
The two benchmark definitions are identical, except for the method used to check if the search character (|
) is found in the string:
match()
method is called on the regular expression FILTERS
with the input string str
. If the regex finds a match, it sets the result variable result
to 1; otherwise, it sets result
to 0.indexOf()
method is called on the string str
with the character |
as an argument. If the character is found in the string, the function returns a non-negative index; if not, it returns -1.Pros and Cons
indexOf()
for simple character searches.Library Usage
There is no external library used in these benchmark definitions. The match()
method is a built-in JavaScript function, while the indexOf()
method is also part of the standard API.
Special JavaScript Features
There are no special JavaScript features explicitly mentioned in these benchmark definitions. However, it's worth noting that modern browsers often provide additional functionality or optimizations for certain methods (e.g., let
and const
declarations are used extensively in many web applications).
Alternatives
Other alternatives to regex and indexOf()
could include:
includes()
method (introduced in ECMAScript 2015), which returns true if the string includes the specified value.String.prototype.search()
).However, for most use cases, regex and indexOf()
remain popular choices due to their simplicity and effectiveness.