orocannoneer
orocannoneer

Reputation: 3

jQuery contains multiple strings optimization

I am writing a Greasemonkey script for hundreds similar pages.

And want to do something if AA or AB or AC...etc in $("#cont > h2")

So I tried:

var 1stgroup = new Array(40)
1stgroup [0] = $("#cont > h2:contains('AA')")
1stgroup [1] = $("#cont > h2:contains('AB')")
1stgroup [2] = $("#cont > h2:contains('AC')")
...
1stgroup [39] = $("#cont > h2:contains('BN')")

for (i =0; i < 40 ; i++) {
    if (1stgroup.text())       {
    //do something here
    };
};

And than group 2~7.

It works, but looks redundant...

How can I optimize it?

Sorry for my poor English and thanks for every reply.

Upvotes: 0

Views: 472

Answers (1)

Matt
Matt

Reputation: 75317

  • DOM traversal is the slowest part in JavaScript, so it makes sense to traverse the DOM as few times as possible.
  • :contains() is a Sizzle extension, and is not part of CSS3, and so is not optimized by browsers. It will be slow.

With this in mind, I'd do something like this;

var matches = ['AA', 'AB', 'AC'];

$('#cont > h2').filter(function () {
    var text = $(this).text();

    for (var i=0;i<matches.length;i++) {
        if (text.indexOf(matches[i]) !== -1) {
            return true;
        }
    }

    return false;
}).each(function () {
    // do something with each of these
});

Another thing you could so is sort the matches array and then use a search algorithm (e.g. binary search) which is smarter than linear search to detect whether the text is a match or not.

Upvotes: 4

Related Questions