In this post it's said that precompiling your regular expressions will improve script performance. The author proves it by performance test. However, as far as I understand, the post is talking about the cases when you use your regular expressions repeatedly. What if there are lots of regular expressions in the script, but each is used only once? Will there be a performance benefit in precompiling regex which is used only once throughout the script?
-
You may get some perceived benefit by compiling up front while the page is loading and users expect a bit of slowness. But that's just shifting the work to some other time, it doesn't save anything and the difference will likely be imperceptible. – RobG Feb 18 '13 at 23:50
3 Answers
I don't believe the performance test that you linked is conclusive. If you look at the results, the difference is negligible because the regex isn't complex enough. Take a look at this test for a little better answer.
Either way, storing a regex value will only provide a performance increase if the regex is used more than once. This performance increase is solely due to the initial compilation overhead for the regex itself. If you are storing the regex in a variable then it will still be compiled the first time just as a literal will be compiled the first time. The difference happens when the stored regex is used a second time and it is already compiled whereas the literal regex would have to be compiled again.

- 1,162
- 10
- 17
-
1There's both compilation time, and also object creation time (though that's less significant). A literal regex will be compiled only once, but if it's used a loop, a new regex *object* will be created for it, for each loop pass. To avoid this, store it in a variable outside the loop. – Doin Dec 18 '16 at 14:45
If it's only used once - then just use regexp literal.
Your point is valid - it only makes sense when you use the same regular expression a lot.

- 249,484
- 69
- 436
- 539
-
That is what I suspected. But I'm losing the point of the aforementioned post then. Because it is just about everything, be it regex, string, function or any other value: if it is used repeatedly, it would be more efficient to assign it to the variable. What am I missing? – tch3r Feb 18 '13 at 23:59
-
2@user2061071: not an assignment, but a *compilation* step is expensive. Though it's valid for functions as well, because it's a declaration step there you may avoid if you store an anonymous function in a variable – zerkms Feb 19 '13 at 00:01