What is more efficient?:
var text="ABCdef";
var lowerVersion=text.toLowerCase();
if (lowerVersion=='abcdef' || lowerVersion=='asdfgh' || lowerVersion=='zxcvbn'){...
or
var text="ABCdef";
if (text.toLowerCase()=='abcdef' || text.toLowerCase()=='asdfgh' || text.toLowerCase()=='zxcvbn'){...
i.e. is variable creation more expensive than running toLowerCase() several times?
Thanks.
This is JavaScript. The answer is going to be: It depends. It depends on what engine you’re using, on your data, on the other things in the context, on whether the first or last match matches, on alternate Tuesdays…
But creating variables in JavaScript is very fast. In contrast, the repeated calls version asks the interpreter to make multiple function calls, and function calls (while fast by any real measure) are slow compared to most other operations. The only way that’s going to be as fast is if the interpreter can figure out that it can cache the result of the call, which is tricky.
Taking @Felix’s performance test and making it pessimistic (e.g., worst case and none of them match) suggests that even Chrome can’t optimize it enough to make the repeated function calls not come out worse. I didn’t do any comprehensive tests, but Chrome, Firefox, and Opera all came out about 60% slower.
You have an alternative, of course:
All of this is premature optimisation, though, which is bad enough generally but particularly bad with JavaScript and the varying environments in which it runs complicating things.
The better question is: What’s clearer and more maintainable?