Most of Node.js top modules I inspect always define their regexp in the module scope, outside the function using it.
For example, few lines taken from Busboy, the fastest multipart/form-data parser for Node.js:
var RE_SPLIT_POSIX =
/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
function splitPathPosix(filename) {
return RE_SPLIT_POSIX.exec(filename).slice(1);
}
Beside re-usability, is there any speed benefits doing this rather than moving the regexp inside the function? Like that:
function splitPathPosix(filename) {
return /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(filename).slice(1);
}
I know that regexp are compiled for better performance. Does that mean the last code snippet needs to recompiled the regexp every time the function is executed? I would guess that most Javascript engine cache the compiled regexp.
I'm specifically interested in V8/Node.js here, but general knowledge about how other engines work can be interesting as well.