I understand your point. Actually, benchmarking seems particualry difficult
for this one.
I created a mooshell wich creates a list with 1000 Elements, wich have 0-3
classes, with or without base_class.
The list ist cloned for each benchmark and i ran each methos is runned 10
times.
Here are the results:

   - Method1 (my method):
      - return this.set('class',new RegExp(klass).exec(this.get('class')));


   - Method1a (my method, *precompiled RegExp* )
      - regexp=new RegExp(klass)
      - this.each(function(e) { e.set('class',regexp.exec(e.get('class')))
      });


   - Method2 (Roman):
      - return this.set('class', this.get('class').split(' ').filter(
      function(c){return c == this },klass)[0]);
   - Method3 (hazlema):
   -  return this.hasClass(klass) ? this.set("class", klass) : this.erase(
      "class");


Results (1000 items):

   - time1:   0.0000340
   - *time1a: 0.0000216*
   - time2:   0.0000306
   - time3:   0.0000234

It seems to depend on how much items you have what the fastet method is. The
strange thing is that i tried it with 1,50,10,100,500,1000 items and now
Method1a is always faster! Perhaps Firefox is caching the RegExp...

http://mootools.net/shell/J7ySB/

Yann


On Mon, Feb 22, 2010 at 06:47, Sanford Whiteman <[email protected]
> wrote:

> >    - Method1: 0.000265s
> >    - Method2: 0.000297s
> >    - Method3: 0.000279s
>
> > Looks like if my method is slightly faster...
>
> Mmm, something is wrong with your benchmark.
>
> Comparing your regex
>
> [f1] t.set('class',new RegExp('base_class').exec(t.get('class')));
>
> with the straightforward
>
> [f2]    t.hasClass('base_class')   ?   t.set('class','base_class')   :
> t.erase('class');
>
> averaging over 10 runs of 1000 function calls each, the regex approach
> is markedly slower.
>
> [f1]:
>
>  .016 when base_class is present on the element
>  .012 when base_class is not present
>
> [f2]:
>
>  .007 when base_class is present
>  .004 when base_class is not present
>
> You can eke out more performance by compiling the RegEx, but the basic
> approach still beats it out significantly, 50-100% faster depending on
> whether the target class is present.
>
> [f1-compiled]:
>
>  .011 when base_class is present on the element
>  .008 when base_class is not present
>
> See http://mootools.net/shell/B8pPc/7/.
>
> - S.
>
>

Reply via email to