How often does JavaScript recompile regex literals in functions? -
How often does JavaScript recompile regex literals in functions? -
given function:
function dothing(values,things){ var thatregex = /^http:\/\//i; // created 1 time or on every execution? if (values.match(thatregex)) homecoming values; homecoming things; }
how javascript engine have create regex? 1 time per execution or 1 time per page load/script parse?
to prevent needless answers or comments, favor putting regex outside function, not inside. question behavior of language, because i'm not sure up, or if engine issue.
edit:i reminded didn't mention going used in loop. apologies:
var newlist = []; foreach(item1 in listofitems1){ foreach(item2 in listofitems2){ newlist.push(dothing(item1, item2)); } }
so given it's going used many times in loop, makes sense define regex outside function, that's idea.
also note script rather genericized purpose of examining behavior , cost of regex creation
there 2 "regular expression" type objects in javascript. regular look instances , regexp object.
also, there 2 ways create regular look instances:
using /regex/ syntax and using new regexp('regex');each of these create new regular look instance each time.
however there 1 global regexp object.
var input = 'abcdef'; var r1 = /(abc)/; var r2 = /(def)/; r1.exec(input); alert(regexp.$1); //outputs 'abc' r2.exec(input); alert(regexp.$1); //outputs 'def'
the actual pattern compiled script loaded when utilize syntax 1
the pattern argument compiled internal format before use. syntax 1, pattern compiled script loaded. syntax 2, pattern compiled before use, or when compile method called.
but still could different regular look instances each method call. test in chrome vs firefox
function testregex() { var localreg = /abc/; if (testregex.reg != null){ alert(localreg === testregex.reg); }; testregex.reg = localreg; } testregex(); testregex();
it's little overhead, if wanted 1 regex, safest create 1 instance outside of function
javascript regex
Comments
Post a Comment