JavaScript replace with callback - performance question
Posted
by Tomalak
on Stack Overflow
See other posts from Stack Overflow
or by Tomalak
Published on 2010-03-18T22:28:05Z
Indexed on
2010/03/18
22:31 UTC
Read the original article
Hit count: 424
In JavaScript, you can define a callback handler in regex string replace operations:
str.replace(/str[123]|etc/, replaceCallback);
Imagine you have a lookup object of strings and replacements.
var lookup = {"str1": "repl1", "str2": "repl2", "str3": "repl3", "etc": "etc" };
and this callback function:
var replaceCallback = function(match) {
if (lookup[match])
return lookup[match];
else
return match;
}
How would you assess the performance of the above callback? Are there solid ways to improve it? Would
if (match in lookup) //....
or even
return lookup[match] | match;
lead to opportunities for the JS compiler to optimize, or is it all the same thing?
© Stack Overflow or respective owner