var html = "<p>A</p><table><tr><td>1</td><td>2</td></tr></table><p>B</p>";
/<table\b[^>]*>/i.test(html)
/<table\b[^>]*>/i.exec(html)
html.match(/<table\b[^>]*>/i)
html.toLowerCase().indexOf('<table')
html.search(/<table\b[^>]*>/i)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
test | |
exec | |
match | |
indexOf | |
search |
Test name | Executions per second |
---|---|
test | 9124243.0 Ops/sec |
exec | 7598622.0 Ops/sec |
match | 7244513.0 Ops/sec |
indexOf | 17055356.0 Ops/sec |
search | 8908225.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
What is being tested?
The provided benchmark tests the performance of different regular expression (regex) methods in JavaScript for searching and finding a specific pattern in a string, in this case, a table element (<table>
) within an HTML string.
Options compared:
i.test(html)
- This method tests if the specified regex pattern exists at the end of the search.i.exec(html)
- This method executes the regex pattern on the search string and returns an array with match data if found.html.match(/<table\\b[^>]*>/i)
- This uses the built-in String.prototype.match()
method to find all occurrences of the regex pattern in the string.html.toLowerCase().indexOf('<table')
- This uses the String.prototype.indexOf()
method with a lowercased version of the search string, looking for the first occurrence of the specified substring.html.search(/<table\\b[^>]*>/i)
- This method searches for the regex pattern in the string and returns the index of the match (0 if not found).Pros and cons of each approach:
i.test(html)
: Pros:true
if the pattern exists anywhere in the string, not just at the end.i.exec(html)
: Pros:test()
due to additional overhead.html.match(/<table\\b[^>]*>/i)
: Pros:html.toLowerCase().indexOf('<table')
: Pros:html.search(/<table\\b[^>]*>/i)
: Pros:test()
, but returns the index of the match instead of just a boolean value.Library and its purpose:
In this benchmark, the String.prototype.match()
method is used in the "match" test case. This method takes two arguments: a regex pattern and a string to search for the pattern. It returns an array containing any matches found in the string, or null if no matches are found.
Special JS feature or syntax:
In this benchmark, the \\b
special sequence is used within the regex patterns. \b
is a word boundary that matches either the empty string (at the beginning or end of a word) or any single character that is not alphanumeric. This helps improve performance by avoiding partial word matches.
Alternatives:
If you need to search for regular expressions in strings, other alternatives might include:
String.prototype.replace()
with a regex pattern and a replacement function.These alternatives might offer better performance, more features, or flexibility depending on your specific use case and requirements.