<!--your preparation HTML code goes here-->
var string = "Hello world!";
var regex = /world/;
regex.test(string);
string.includes("world")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
regex.test | |
string.includes |
Test name | Executions per second |
---|---|
regex.test | 23823738.0 Ops/sec |
string.includes | 98594952.0 Ops/sec |
The benchmark provided is designed to compare the performance of two JavaScript methods used for string matching: RegExp.test()
and String.includes()
. Both methods are commonly used in JavaScript for checking the presence of a substring or pattern within a string, but they have different implementations and use cases.
RegExp.test(string)
: This method tests whether a regular expression matches a specified string. In this benchmark, the regular expression /world/
is used to check for the presence of the substring "world" in the string "Hello world!".String.includes("world")
: This method checks if a given substring exists within a string. In this case, it checks if the substring "world" is present in "Hello world!".RegExp.test()
Pros:
Cons:
String.includes()
Pros:
String.includes()
considerably exceeds the performance of RegExp.test()
in the executed tests, making it a better choice for simple use cases.Cons:
In the provided benchmark results, String.includes
achieved an impressive execution rate of approximately 98,594,952 executions per second, whereas RegExp.test
yielded only about 23,823,738 executions per second. This significant difference highlights the performance advantage of using String.includes()
for basic substring checks.
Context of Use: The choice between RegExp.test()
and String.includes()
should be dictated by the specific needs of the application. If the requirement is merely to check for a substring's existence, String.includes()
is the superior choice due to its simplicity and efficiency. If pattern matching is required, RegExp.test()
would be more suitable.
Alternatives: Besides using RegExp.test()
and String.includes()
, there are other alternatives for string matching in JavaScript:
String.indexOf()
: An older method that returns the position of the first occurrence of a specified substring, returning -1
if not found. While it accomplishes similar tasks, its use is generally discouraged in favor of String.includes()
for presence checks.String.match()
: Returns an array of matches when a string is tested against a regular expression. Though more comprehensive, it is less efficient than String.includes()
for simple existence checks.String.search()
: Similar to RegExp.test()
, this method returns the index of the first match of a regular expression within a string.In summary, this benchmark effectively demonstrates the performance differences between using regular expressions and simpler string methods, offering guidance for developers on choosing the right tool for string matching based on context and performance requirements.