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?
+1 to Annie about perf benchmarks.
But I would go with
return lookup[match] || match;
Not only is it just a single retrieval of the property (rather than -- barring optimization -- two, as in your earlier examples), but it's also shorter and (this is not always true of shorter code) clearer to any half-experienced JavaScript coder. It will tend to throw novices a bit, but one of the first things you want to teach novices is how the special (and excellent) ||
and &&
work in JavaScript, so...
It also works around a couple of (very) edge cases in some implementations. (Example: 'toString' in {}
should be true
[all objects inherit toString
from the Object
prototype], but it's false
in Microsoft's JScript.)
Regarding optimizing: Barring the glaringly obvious (don't make your loop condition a function that has to go count things if it can be an invariant, avoid duplicating lookups unnecessarily), even absent the general discussion of whether it's worth worrying about this stuff before you see a problem (sometimes called "premature optimization"), it's especially true of JavaScript for the general web. Different micro-optimizations have different results in different implementations, sometimes conflicting results ("A" being better in Internet Explorer but much worse in FireFox, and the converse). Mostly it's a matter of wait until you see a specific problem, then address that specific problem.
I prefer simplicity and clarity, unless I have a strong reason to believe that something clunkier is going to give me a measurable, real-world improvement.
You can use a benchmark tool like JSLitmus to benchmark different approaches. Be sure to test different browsers.