Why is the third option better than regex?

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]) { ... }
+5
source share
7 answers

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.)

+6
source

, , ... 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 , , , . , .

+5
  • .
  • .
  • , - , .

, , , O (n), - O (1) .

, / , .

+2

===, , , , O(N), JS .

RegExp, RegExps , , , , . , , , JS-, , .

- , , , , - - .

, switch .

( ), ( , , webkit) switch, if, , regexp last.

+1

, ! , . , , , , :)

, jsPerf (http://jsperf.com/string-tests) , , Chrome, , . .

, :

  • , : - , , , . , - - , .
  • , , , . - . , , , . , , ; , , , , .
+1

-, n. "type ==" .

0

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.

0
source

All Articles