# Filtering long lists of images

I have to filter some very long lists of images many times (thousands, even 10/15k, even much more), so performance is important.

First solution:

var image_match = [];
$('#'+id_canvas+' image').each(function(i, el) { if (el.attributes.x.value === x && el.attributes.y.value === y) { image_match.push($(this));
};
});


Second solutions:

var image_match = $('#'+id_canvas+' image[x='+x+'][y='+y+']');  Which solution is faster? Or maybe a non-jQuery solution? Also, I can often know how many images will pass the test so when I found that number of images I can stop the search, like this: var image_match = []; var target_number = 3;$('#'+id_canvas+' image').each(function(i, el) {
if (el.attributes.x.value === x && el.attributes.y.value === y) {
image_match.push(\$(this));
if (image_match.length === target_number) {
return false;
};
};
});


Can I do the same thing in the second solution?

• if the images are always the same, cache all images selector and then filter with your each that cache. Also you might be able to map a mapping of x-y pairs to the image elements that match that. Need more use context – juvian Aug 1 '17 at 14:48
• At last I will use simple for loop and when possible I will cache the images. I don't know how to use a map in this contest. – fabio Aug 2 '17 at 23:41

If you want to know which is the fastest solution you will have to measure them. Though I would guess the second is faster. You could test a direct document.querySelector though jQuery should be passing the query through pretty much as is. The one suggestion I would make is instead of interpolating your image_id each time give all of the images a class and use a class selector.
It looks like you don't need JQuery, so it should be faster to not use it. Use document.querySelector and for(var i = 0; i < result.length; i++) {f(result[i])} instead. Also, you can use return; instead of return false;.