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?

有帮助吗?

解决方案 3

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.

其他提示

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.

I think this depends on browser implementation and we cannot conclusively say one approach is better.

See the different results in firefox and chrome.

enter image description here

I am confused why chrome gives faster results for non-recompiled regex though.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top