I think the regex is pretty fast, and the third option is confusing. What do you think?
http://jqfundamentals.com/book/ch09s12.html
// old way if (type == 'foo' || type == 'bar') { ... } // better if (/^(foo|bar)$/.test(type)) { ... } // object literal lookup if (({ foo : 1, bar : 1 })[type]) { ... }
I humbly disagree with Rebecca Murphy and vote for simplicity, for the first option.
I think regex is pretty fast. Machine code is even faster, but we don't use it.
The third option is confusing. It only bothers you if you are not familiar with the trick. (And for people who are not used to seeing a regular expression to compare two strings, the second option will be even more confusing.)
, , ... http://jsbin.com/uzuxi4/2/edit
Regex, , , , , . . , , .
, , . , ().
Edit: , , : http://jsbin.com/uzuxi4/4/edit
function __hash() { ... var type = 'bar'; var testobj = { foo : 1, bar : 1 }; var c = 0; for (i = 0; i < 1000; i++) { if (testobj[type]) { for (j = 0; j < 10000; j++) { if (testobj[type]) { c++; } } } } ... }
, , 500 , , , . , .
, , , O (n), - O (1) .
, / , .
===, , , , O(N), JS .
===
O(N)
RegExp, RegExps , , , , . , , , JS-, , .
- , , , , - - .
, switch .
( ), ( , , webkit) switch, if, , regexp last.
, ! , . , , , , :)
, jsPerf (http://jsperf.com/string-tests) , , Chrome, , . .
, :
-, n. "type ==" .
For simplicity and readability, the first will win every time. It may not be so fast, but who cares if it is not in a very running cycle.
Good compilers should optimize such things.