var REGEX_1 = /"{0,1}cpf"{0,1}[:=]"{0,1}([\w\s]{1,})/;
var REGEX_2 = /"{0,1}cpf"{0,1}[:=]\"{0,1}([\w\s]+)/;
var REGEX_3 = /"{0,1}cpf"{0,1}[:=]"{0,1}([^ ,]*)/;
REGEX_1.test("cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12")
REGEX_2.test("cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12")
REGEX_3.test("cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12,cpf=12")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
REGEX_1 | |
REGEX_2 | |
REGEX_3 |
Test name | Executions per second |
---|---|
REGEX_1 | 10136053.0 Ops/sec |
REGEX_2 | 10001486.0 Ops/sec |
REGEX_3 | 9609164.0 Ops/sec |
Measuring JavaScript performance is a crucial task, especially when it comes to regular expressions (regex). The provided benchmark definition and test cases offer a great insight into the performance comparison of different regex patterns.
Benchmark Definition
The script preparation code provides three regex patterns:
REGEX_1
: \ "{0,1}cpf"{0,1}[:=]\"{0,1}([\\w\\s]{1,})/
REGEX_2
: \ "{0,1}cpf"{0,1}[:=]\\\"{0,1}([\\w\\s]+)/
REGEX_3
: \ "{0,1}cpf"{0,1}[:=]\"{0,1}([^ ,]*)/
These regex patterns are designed to match the CPF (Cadastro de Pessoas Físicas) format in Brazil.
Options Comparison
The options being compared are:
REGEX_1
: The original pattern with optional whitespace and the matched group capturing any word characters or whitespace.REGEX_2
: A modified version of REGEX_1
that uses an extended slash (\
) to match literal forward slashes (/
), but only when preceded by a non-literal forward slash. This is unnecessary, as the pattern already matches whitespace.REGEX_3
: The most simplified version, which captures the CPF number in a single group without any optional whitespace.Pros and Cons of each approach:
REGEX_1
:REGEX_2
:REGEX_3
:Library Usage
The benchmark definition uses the built-in JavaScript function test()
for each regex pattern, which is part of the String prototype. This function tests whether the regular expression matches the specified string and returns an object with properties indicating the success or failure of the test.
Special JS Features or Syntax
There are no special JS features or syntax used in this benchmark definition.
Alternatives
Other alternatives for testing regex performance in JavaScript include:
Intl
API, which provides standardized support for regex patterns across browsers.Keep in mind that the specific approach and libraries used will depend on the project's requirements and the desired level of optimization.