chjj / zest

An absurdly fast CSS selector engine.
MIT License
238 stars 14 forks source link

RegExp creation #1

Closed arextar closed 12 years ago

arextar commented 12 years ago

One thing that I think could help speed up zest is to assign regular expressions used as variables within the closure, and then reference them where they're needed.

Example (L55)

$ = /^([+-])?(\d+)?n([+-])?(\d+)?$/.exec($);

A variable (such as r_nth) can be declared at the top of the closure (where document and window are defined)

var window = this
  , document = this.document
  , r_nth =  /^([+-])?(\d+)?n([+-])?(\d+)?$/;

...and then be used as such:

 $ = r_nth.exec($);

The following jsperf shows that it's a little faster to use this method (and every little bit helps) http://jsperf.com/regexp-creation

arextar commented 12 years ago

After testing I've found the difference may be negligible. I'll keep investigation

chjj commented 12 years ago

It my own benchmarks it seems that taking the time to access a (possibly mutable) variable in another scope is actually slower. It would make sense that an engine could optimize a regex out when it's not tied to a variable - it can treat it as though it's not mutable, as if it were a constant, and it skips the step of accessing a variable in another scope.

Although I'm not sure that's how it works, and I'm definitely not sure that's how it works in every engine, it would make sense to do it that way. But as you said, the benchmarks seem fairly close. In my experience, when a regex is not tied to a variable, it tends to be faster at least in v8. Even IE doesn't seem to have much of a problem with it.

arextar commented 12 years ago

Yeah, great work on this engine though, I always thought Sizzle could be beaten and this has definitely pulled it off.

chjj commented 12 years ago

Thanks. Unfortunately, I don't know if it will ever be used much use because it's kind of annoying to put another selector engine in jquery, or any other dom library out there. Thank you for your interest though.