var string = "Hello world123!";
var regex = /(abc|bcd|cde|def|efg|fgh|ghi|hij|ijk|jkl|klm|lmn|mno|nop|opq|pqr|qrs|rst|stu|tuv|uvw|vwx|wxy|xyz|012|123|234|345|456|567|678|789)+/i;
var sequence = ["abc", "bcd", "cde", "def", "efg", "fgh", "ghi", "hij", "ijk", "jkl", "klm", "lmn", "mno", "nop", "opq", "pqr", "qrs", "rst", "stu", "tuv", "uvw", "vwx", "wxy", "xyz", "012", "123", "234", "345", "456", "567", "678", "789"]
regex.test(string);
sequence.some(word => string.toLowerCase().includes(word.toLowerCase()));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
RegEx.test | |
String.includes |
Test name | Executions per second |
---|---|
RegEx.test | 3534689.0 Ops/sec |
String.includes | 339019.4 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition
The benchmark is designed to compare two approaches for searching an array in a string: using a regular expression (Regex.test
) and using the String.includes
method with a callback function.
Options Compared
Two options are compared:
sequence
array.String.includes
method with a callback function to search for an element in the sequence
array. The callback function converts both the string and the sequence elements to lowercase before comparing.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Regex.test
Pros:
Cons:
String.includes with callback
Pros:
Cons:
Library: RegExp
The RegExp
object is used in the regex-based approach. It provides methods for working with regular expressions, such as testing whether a string matches a pattern (test()
), searching for a pattern in a string (exec()
), and replacing text using a regex pattern (replace()
).
Special JS Feature/Syntax: None
There are no special JavaScript features or syntaxes used in this benchmark.
Other Alternatives
Some other approaches that could be considered for comparing array searches in strings include:
Array.prototype.some()
method with a callback function.String.indexOf()
method to search for an element in the string.However, these alternatives may not provide the same level of efficiency and readability as the two options compared in this benchmark.