Caching vs RegExp Literal

JavaScript performance comparison

Revision 9 of this test case created by Ian Nartowicz

Info

Does storing regular expressions in a variable help?

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var result;
    var rLiteral = /\w+@\w+(?:\.\w+)*/i;
    var rRegexp = new RegExp("\\w+@\\w+(?:\\.\\w+)*", "i");
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
literal
result = /\w+@\w+(?:\.\w+)*/i.test("j@g.com");
pending…
Cached literal
result = rLiteral.test("j@g.com");
pending…
Constructor
result = (new RegExp('\\w+@\\w+(?:\\.\\w+)*', 'i')).test("j@g.com");
pending…
Cached constructor
result = rRegexp.test("j@g.com");
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment