If a regular expression is expected to be used multiple times, it is better to assign it to a variable before the uses. For example, do:
let str = 'a';
let regexp1 = /^\d+$/;
for(let i = 0; i < 1000; ++i)
regexp1.exec(str);
instead of:
let str = 'a';
for(let i = 0; i < 1000; ++i)
/^\d+$/.exec(str);
Using https://jsbench.me/ to benchmark them, the second snippet is roughly 8.61% slower.
Further Explanation
Some people may doubt the effectiveness in performance improvement because MDN explains that:
Regular expression literals provide compilation of the regular expression when the script is loaded. If the regular expression remains constant, using this can improve performance.
However, this does not mean the literal carries no overhead during runtime – a RegExp
object is still yet to be constructed during runtime. In fact, the ECMAScript standard says:
A regular expression literal is an input element that is converted to a RegExp object each time the literal is evaluated.
The first code snippet is faster because the JS engine constructs a RegExp
object in each iteration from the precompiled regular expression in the second code snippet, while it only constructs once in the first code snippet.