var reConstructor = new RegExp('^[0-9a-fA-F]{24}$')
var reSimpleConstructor = RegExp('^[0-9a-fA-F]{24}$')
var reLiteral = /^[0-9a-fA-F]{24}$/
reLiteral.test('132abc67219f019afe12901a')
reSimpleConstructor.test('132abc67219f019afe12901a')
reConstructor.test('132abc67219f019afe12901a')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
literal | |
RegExp | |
Constructor |
Test name | Executions per second |
---|---|
literal | 6191115.5 Ops/sec |
RegExp | 5552362.5 Ops/sec |
Constructor | 5835731.0 Ops/sec |
Let's break down the provided benchmark and its test cases.
Benchmark Definition JSON
The provided JSON defines a JavaScript microbenchmark that tests different approaches to creating regular expressions in JavaScript. The three options being compared are:
RegExp
object is created using the RegExp
constructor, passing the same string as its argument.The script preparation code defines these three constructors:
reLiteral
: A literal string used directly in the regex pattern.reSimpleConstructor
: A simple RegExp
object created using the RegExp
constructor.reConstructor
: A custom regular expression constructor function.Pros and Cons of each approach
RegExp
object using the constructor can provide some benefits, such as avoiding unnecessary memory allocations and improving cache locality. However, this approach still involves creating a new object, which might incur some overhead.Other considerations
The benchmark also includes two test cases:
reLiteral.test('132abc67219f019afe12901a')
: Tests the literal approach with a specific input string.reSimpleConstructor.test('132abc67219f019afe12901a')
and reConstructor.test('132abc67219f019afe12901a')
: Test the simple RegExp and custom constructor approaches, respectively.JavaScript features used
The benchmark uses JavaScript's regular expression syntax and object creation mechanisms to create and test the different constructors. Specifically, it utilizes:
RegExp
constructor to create new regular expression objects.test()
method on a regular expression object to evaluate strings against it.function
keyword.Library usage
There are no external libraries used in this benchmark.
Special JavaScript features and syntax
The custom constructor approach uses a feature of JavaScript called "arrow functions" (introduced in ECMAScript 2015) to define the regular expression constructor function.