What is faster/more efficient - $(".selector").height() vs $(".selector").eq(0).height()

313 views Asked by At

I have 20 x element.selector with same (100px) height and I need to get their height (100px, not 2000px).

What is faster/more efficient to do?

$(".selector").height() 

or

$(".selector").eq(0).height()
1

There are 1 answers

4
tjati On BEST ANSWER

I raced them for you.

            run 1           run 2           run 3           run 4
with_eq:    1956.769ms      1875.220ms      1930.814ms      1895.359ms
no_eq:      1851.168ms      1861.596ms      1804.347ms      1829.207ms

And it seems, that not using eq(0) is slightly faster. It's obvious, because you save another function call on your jquery object. Not calling something is always faster than to call.

This is my test case:

// noprotect

console.time('with_eq');
for (var i = 0; i<40000; i++) {
  $(".foo").eq(0).height();
}
console.timeEnd('with_eq');

console.time('no_eq');
for (var i = 0; i<40000; i++) {
  $(".foo").height();
}
console.timeEnd('no_eq');
    .foo { height:100px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <div class="foo">Hi.</div><div class="foo">Hi.</div><div class="foo">Hi.</div>
 <div class="foo">Hi.</div><div class="foo">Hi.</div><div class="foo">Hi.</div>
 <div class="foo">Hi.</div><div class="foo">Hi.</div><div class="foo">Hi.</div>
 <div class="foo">Hi.</div><div class="foo">Hi.</div><div class="foo">Hi.</div>
 <div class="foo">Hi.</div><div class="foo">Hi.</div><div class="foo">Hi.</div>
 <div class="foo">Hi.</div><div class="foo">Hi.</div><div class="foo">Hi.</div>
 <div class="foo">Hi.</div><div class="foo">Hi.</div><div class="foo">Hi.</div>
 <div class="foo">Hi.</div><div class="foo">Hi.</div><div class="foo">Hi.</div>
 <div class="foo">Hi.</div><div class="foo">Hi.</div><div class="foo">Hi.</div>