Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why the third option is better than regex?

I think 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]) { ... }
like image 221
Nick Vanderbilt Avatar asked Oct 15 '10 18:10

Nick Vanderbilt


2 Answers

I'll humbly disagree with Rebecca Murphey 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's only confusing if you're unfamiliar with the trick. (And for people not used to seeing regex to compare two strings, second option will be even more confusing.)

like image 55
Nikita Rybak Avatar answered Oct 05 '22 01:10

Nikita Rybak


I just made a rudimentary benchmark and I'm honestly not sure how she got those results... http://jsbin.com/uzuxi4/2/edit

Regex seems to scale the best, but the first is by far the fastest on all modern browsers. The last is excruciatingly slow. I understand the complexity theory between the three, but in practice, it doesn't seem that she's correct.

Let alone the fact that the first also has the best readability, it also seems to be the fastest. I even nested loops to take advantage of any browser caching of literal tables or constants (to no avail).


Edit: It appears that when an object is explicitly created, she is indeed correct, however: 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++; }
      }
    }
  }

  ...
}

We see that once the object has an internal reference, the seek time drops to about 500 ms which is probably the plateau. Object key lookup may be the best for larger data-sets, but in practice I don't really see it as a viable option for every-day use.

like image 35
David Titarenco Avatar answered Oct 05 '22 01:10

David Titarenco