jquery attr() vs getAttribute()

JavaScript performance comparison

Revision 2 of this test case created by Roy

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div id="section1">
   <span class="top">top1</span>
   <div class="middle">
                middle1
                <span class="inner">inner1</span>
   </div>
   <div class="bottom">bottom1</div>
</div>
<div id="section2">
   <span class="top">top2</span>
   <div class="middle">
                middle2
                <span class="inner">inner2</span>
   </div>
   <div class="bottom">bottom2</div>
</div>
<script>
var elem = $("#section2");
var rawElem = document.getElementById("section2");
</script>

Preparation code output

top1
middle1 inner1
bottom1
top2
middle2 inner2
bottom2

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
attr
elem.attr("id");
pending…
orig getAttribute
elem[0].getAttribute("id");
pending…
raw getAttribute
rawElem.getAttribute("id");
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

2 comments

Roy (revision owner) commented :

The getAttribute performance is slightly better than your original test indicated. For the getAttribute test, you were paying the cost each time of resolving the "0" property of the jQuery object.

I added a new "raw getAttribute" that stores that resolution off into a variable to be used by the test runs.

김용준 commented :

이게 뭔가요?

Add a comment