Search code examples
javascriptsizzle

Sizzle push apply


Why would the Sizzle selector engine use push.apply( results.... ) over results.push(...) it seems unnecessary to me. Can someone explain the motivation?

To elaborate, I've become interested in writing/borrowing bits from sizzle for a lighter weight selector engine. I figure I don't need some things like :contains(text) which would reduce the weight even further. So reading through the source I see

var arr = [],
    push = arr.push
    results = results || [];
 ....
 push.apply( results, context.getElementsByTagName( selector ) );

The code makes sense, except wouldn't it be simpler to use

results.push( context.getElementsByTagName( selector ) );

I don't intend to be naggy about such a minor convention, I just want to know if I'm missing something like a context issue.


Solution

  • It is instead of:

    results.concat(array)
    

    Because concat creates an extra array, but push.apply won't:

    push.apply(results, array)
    

    The results array is cached and no extra arrays are created.

    But you could also do:

    results.push.apply(results, array)
    

    I'm not sure why the need for arr.

    Edit:

    I'm thinking the need for the extra arr might be to convert the pseudo-array that getElementsByTagName returns into a real array.