1
\$\begingroup\$

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?

\$\endgroup\$
  • 2
    \$\begingroup\$ 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 \$\endgroup\$ – juvian Aug 1 '17 at 14:48
  • \$\begingroup\$ 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. \$\endgroup\$ – fabio Aug 2 '17 at 23:41
1
\$\begingroup\$

I suspect that performance with 15k images will be bad no matter what you do. You might want to rethink your UI.

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.

As to your last question, I don't know of anyway to do it using pure css and there would probably be little advantage anyway.

\$\endgroup\$
  • \$\begingroup\$ Indeed we're seeing code that is impossible to be "user-perceived-performant". UI/UX should be revisited here. Architecturally, the performance might get improved by delegating the heavy lifting to back end and doing tricky caching, but this is definitely out-of-scope for this site. \$\endgroup\$ – Igor Soloydenko Oct 6 '17 at 22:43
0
\$\begingroup\$

(Inspired in part by Marc Rohloff's answer)

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;.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.