Why is this cycle getting slower?

for (i = 0; i < $('body > p font i').length; i++) {
    current = [$('body > p font i').eq(index), $('body > p font i').eq(index).index('body > p font u, body > p font i')];
    getState(current[1]);
}

function getState(index) {
    // Lookup the object index, then crawl up until you find a match
    while ($('body > p font u, body > p font i').eq(--index).filter('u').length == 0);
    console.log($('body > p font u, body > p font i').eq(index).text());
}

Pretty simple question. I repeat the jQuery result set against the selector filter until I find a match, going up the result set when I go.

The longer this cycle, the slower it becomes almost exponentially.

+4
source share
1 answer

You do the serialization in the DOM tree at each iteration, which is an expensive operation, the solution is the cache:

var nodes = $('body > p font i');
for (var i = 0, size = nodes.length; i < size; i++) {
    current = [nodes.eq(index),nodes.eq(index).index('body > p font u, body > p font i')];
}
+2
source

Source: https://habr.com/ru/post/1663353/


All Articles