Ok, let's find out.
(Open the console and run the code snippet above to see if there are any results for your browser.)
In Node.js 0.10.36 (V8 3.14.5.9):
1: 65ms 2: 0ms
In io.js 1.6.3 (V8 4.1.0.27):
1: 32ms 2: 0ms
So, I think the answer to your question is YES , the V8 is able to automatically cache the regular expression.
EDIT:
Despite the fact that the V8 is capable of such optimization, in fact, it cannot always use this optimization. V8 has many complex heuristics for different cases, for example, when to embed a function, when to optimize a function, when to de-optimize a function, etc. If you are not a V8 developer, many of these heuristics look strange or unexpected, or both.
Not being a V8 developer myself, I don't know the answer to a specific question about whether regular expressions are always cached automatically. However, even if I know the answer, it may change in the future. So when you write code, I would still recommend storing the regular expression in such a way that it is clear what the intent is for this variable. And for the example above, this means that output the variable regex out of the isFooBar() function.
Another problem is how this regular expression is created. The example above and in the OP question is declared with a regular expression literal . However, if you use the new RegExp() constructor, V8 will not be allowed to cache the regular expression, as it may change at run time.
Timothy gu
source share