user12310517
user12310517

Reputation:

Slow JavaScript function, how can I improve it?

I have the following JavaScript function that seems to perform really slow.

This function gets called many times within a loop

function _matches(el, selectors) {

    var result = selectors.filter(function (selector) {
          return [].indexOf.call(document.querySelectorAll(selector), el) !== -1;
    });

    return result.length > 0;
}

Here is an example of how this function is called

// Vertical Loop
rows.map(function (element, row) {

    if (_matches(element, '.ignore')) {
        // do something A
    }

    if (_matches(element, '.empty')) {
        // do something B
    }

    var cols = element.querySelectorAll("th, td");
    // Horizontal Loop
    return cols.map(function (element, ic) {

        if (_matches(element, '.ignore')) {
            // do something A
        }
        if (_matches(element, '.empty')) {
            // do something B
        }
    });
});

I am unsure what the [].indexOf.call(document.querySelectorAll(selector), el) line does or means so I am not sure how to improve the performance of this function.

Upvotes: 0

Views: 205

Answers (1)

user229044
user229044

Reputation: 239521

You're finding all elements in the DOM matching a given selector, then asking whether an element you already have appears in that set. This an extremely inefficient way to tell if the element you already have matches a given selector.

Just use element.matches(selector).

// No:
if (_matches(element, '.ignore')) {
  // do something A
}

// Yes:
if (element.matches('.ignore')) {
  // do something A
}

Upvotes: 1

Related Questions