var searchText = "New";
var testText1 = "NEW ABABABABABAABABAB";
var testText2 = "new ABABABABABAABABAB";
var lowerCaseSearchText = searchText.toLowerCase();
var lowerCaseTestText1 = testText1.toLowerCase();
var lowerCaseTestText2 = testText2.toLowerCase();
console.log(lowerCaseTestText1.includes(lowerCaseSearchText) || lowerCaseTestText2.includes(lowerCaseSearchText));
var regText = new RegExp(searchText, 'i');
var test1NameMatch = testText1.match(regText);
var test2NameMatch = testText2.match(regText);
console.log(test1NameMatch.length > 0 || test2NameMatch.length > 0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
With lower case | |
With regex |
Test name | Executions per second |
---|---|
With lower case | 83864.8 Ops/sec |
With regex | 80881.1 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares two approaches to search for a specific string within a text: the includes
method and regular expressions (regex).
Script Preparation Code
The script preparation code sets up variables:
searchText
: The target string to be searched.testText1
and testText2
: Two example texts containing the target string in different cases (uppercase, lowercase, and a mix of both).lowerCaseSearchText
, lowerCaseTestText1
, and lowerCaseTestText2
: These variables are created by converting searchText
and testText1
to lowercase using the toLowerCase()
method.Html Preparation Code
There is no HTML preparation code provided, which means that the benchmark does not test any specific HTML-related scenarios.
Individual Test Cases
The benchmark consists of two individual test cases:
This test case searches for the target string in both testText1
and testText2
using the includes()
method, which converts the search text to lowercase before performing the search.
Pros:
Cons:
This test case searches for the target string in both testText1
and testText2
using a regular expression (regex). The regex is created with the i
flag, which makes it case-insensitive.
Pros:
includes()
method for complex cases.Cons:
includes()
method due to the overhead of regex parsing.Library: RegExp
The RegExp
object is a built-in JavaScript library that provides support for regular expressions. The new RegExp(searchText, 'i')
expression creates a new regex object with the specified search text and case-insensitive flag.
Special JS Feature/Syntax
There are no special JavaScript features or syntax used in this benchmark.
Other Alternatives
Alternative approaches to searching for strings within texts include:
String.prototype.indexOf()
or Array.prototype.indexOf()
)Keep in mind that these alternatives may not be as efficient or effective as the includes()
method or regex-based approaches for simple cases.