Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of jquery visible

Tags:

jquery

visible

I have a bunch of checkboxes on a page, and I only show a subset of those checkboxes at a time.

I then perform some action which loops through all of the checkboxes and sees if they are checked or not:

e.g.

$(".delete_items").click( function() {
     $('.checkboxes' ).each(function(){
     //do stuff
     }
}

Then I was thinking, well since the user can never interact with the hidden checkboxes, that adding :visible to checkboxes would speed up the loop

e.g.

$(".delete_items").click( function() {
     $('.checkboxes :visible' ).each(function(){
     //do stuff
     }
}

But I don't know if adding :visible adds more overhead. Any thoughts?

like image 342
Mark Steudel Avatar asked Oct 12 '25 20:10

Mark Steudel


1 Answers

:visible will add for sure more overhead, as jQuery has to check several properties whether an element is visible or not:

Elements can be considered hidden for several reasons:

  • They have a CSS display value of none.
  • They are form elements with type="hidden".
  • Their width and height are explicitly set to 0.
  • An ancestor element is hidden, so the element is not shown on the page.

Source — :hidden Selector | jQuery API Documentation

Especially the last point seems to imply traversing the DOM up for every element which adds overhead.

If you just use the class as selector, jQuery can make use of browser functions like getElementsByClass or querySelectorAll.

On the other side, if you perform computational complex actions on these checkboxes, looping over fewer of them might outweigh the previous lookup.

You definitely have to benchmark it yourself.

Update:

Another idea to assign another class to the visible checkboxes and select them with

$('.checkboxes.otherClass')

that should definitely be faster than using :visible.

Update 2:

I created a jsPerf: http://jsperf.com/jquery-visible-test

It might not be the best test case but, at least for me (Chrome 8, Mac OS X 10.6), using :visible is ~45% slower (even worse in Firefox 3.6.13: ~75% slower).

Update 3:

Using two classes seems to be even faster, I updated the test case.

like image 59
Felix Kling Avatar answered Oct 15 '25 18:10

Felix Kling