var testStr = 'QWERtyuioIUYTRE';
var input = 'uioiu';
var inputRegex = new RegExp(input, 'i');
testStr.toLowerCase().includes(input);
inputRegex.test(testStr);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
string.toLowerCase().includes() | |
regex.test() |
Test name | Executions per second |
---|---|
string.toLowerCase().includes() | 39833884.0 Ops/sec |
regex.test() | 59089840.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
The provided JSON represents a benchmark that compares two approaches for case-insensitive string searches: using regex.test()
versus string.toLowerCase().includes()
. Here's a breakdown of what's tested:
Options being compared:
inputRegex.test(testStr)
): This approach uses a regular expression to perform the search. The new RegExp
constructor creates a regex object with the specified input pattern (input
) and flags (in this case, 'i'
, which enables case-insensitive matching).toLowerCase()
+ includes()
: This approach converts the test string to lowercase using toLowerCase()
and then uses the includes()
method to search for the input substring.Pros and Cons of each approach:
inputRegex.test(testStr)
):toLowerCase()
+ includes()
:includes()
. It also avoids creating a new string or using a loop.Other considerations:
Library used:
In this benchmark, no specific library is required or provided beyond the built-in RegExp
class and JavaScript's standard library (String.prototype.toLowerCase()
and String.prototype.includes()
).
Special JS feature/syntax:
This benchmark uses the includes()
method, which was introduced in ECMAScript 2015 (ES6). It's a convenient and efficient way to search for a substring within a string. Note that this feature is widely supported across modern JavaScript engines.
Now, let's look at other alternatives:
testStr.indexOf(input.toLowerCase())
Keep in mind that these alternatives may not be as straightforward to implement or maintain, but they might offer performance improvements in specific scenarios.