var list = ["Hello", 'world', 'hello1', 'world1', 'hello2', 'world2', 'hello3', 'world3'];
var regex = /Hello|world|hello1|world1|hello2|world2|hello3|world3/;
regex.test('Hello');
regex.test('hello2');
regex.test('world3');
list.includes("Hello");
list.includes("hello2");
list.includes("world3");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
RegEx.test | |
String.includes |
Test name | Executions per second |
---|---|
RegEx.test | 11154954.0 Ops/sec |
String.includes | 22983580.0 Ops/sec |
The benchmark provided compares two different approaches for searching for strings in a pre-defined list: using a regular expression (RegEx.test
) versus using the Array.includes
method.
Benchmark Preparation:
["Hello", 'world', 'hello1', 'world1', 'hello2', 'world2', 'hello3', 'world3']
./Hello|world|hello1|world1|hello2|world2|hello3|world3/
.Individual Test Cases:
RegEx.test
method when applied to three different strings: 'Hello'
, 'hello2'
, and 'world3'
..test()
method of a regular expression returns true
if there is a match; otherwise, it returns false
.Array.includes
method, also using the same three strings.includes()
method checks if a particular value exists in the array, returning true
or false
.Array.includes
outperforms RegEx.test
:String.includes
: 22,983,580 executions per secondRegEx.test
: 11,154,954 executions per secondPros:
Cons:
Pros:
Cons:
Array.includes
is often the preferred method due to its clarity and performance.find()
can return the first matching element or undefined
if no matches exist, while indexOf()
returns the index of the occurrence or -1
if not found.Set
may improve lookup performance as it has better time complexity for existence checks compared to arrays.In summary, this benchmark provides a clear comparison of performance metrics between two commonly used JavaScript methods for string searching, emphasizing the strengths and weaknesses of each approach under the scenario presented.