Search code examples
jqueryjquery-selectorssizzle

createPseudo performance


I recently had a quick look at the new jQuery Sizzle, i was wondering if there is any significant performance difference between using Sizzle.matchesSelector or assessing directly the attribute of the element parameter :

$.expr.createPseudo(function(selector) {
  return function( elem ) {
    return elem.getAttribute('data-smth').match(/someRegex/)
  }
}

VS :

$.expr.createPseudo(function(selector) {
  return function( elem ) {
    return $.find.matchesSelector(elem, 'div.someClass[data-smth*=smth]')
  }
}

I find personaly matchesSelector easier since we keep on jquery level and we can add easily some constraints (.someClass in my exemple above)


Solution

  • The difference is that .matchesSelector() is a function that is either native or a custom one created by the Sizzle developers. In the case of a native function, the difference, although .getAttribute() would still be faster, would be lesser. However, in case of a custom function, the difference would be greater, definitely in favor of .getAttribute().

    .matchesSelector(), however, safely queries attributes, so that is something to keep in mind.