user3973971
user3973971

Reputation:

Operations degraded by DOM complexity?

I stumbled across this jsperf.

It tests the relative performance of editing the html of an element accessed by id only or by id via a cached selector.

The element edited is 17 levels deep.

jsperf actually reports that not using the cached selector is faster.

<script src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>
</script>
<div id="container"><div><div><div><div><div><div>
<div><div><div><div><div><div><div>
  <div>
    <div>
    </div>
    <div>
    </div>
    <div class="robotarm">
    </div>
    <div>
      <div id="robotarm">
      </div>
    </div>
    <div class="robotarm">
    </div>
    <div class="robotarm">
    </div>
    <div>
    </div>
  </div>
</div>
</div></div></div></div></div></div></div>
</div></div></div></div></div></div></div>

<div><div><div><div><div><div><div>
</div></div></div></div></div></div></div>
<div><div><div><div><div><div><div>
</div></div></div></div></div></div></div>
<div><div><div><div><div><div><div>
</div></div></div></div></div></div></div>
<div><div><div><div><div><div><div>
</div></div></div></div></div></div></div>
<script>
  Benchmark.prototype.setup = function() {
    function cached() {
      $div = $('#container');
      for (i = 0; i < 1000; i++){
        $div.find('#robotarm').html('foo');
      }
    }

    function raw() {
      for (i = 0; i < 1000; i++){
        $('#robotarm').html('foo');
      }
    }
  };
</script>

However, the performance is atrocious. Why, and why is it better to select without a cached selector?

Upvotes: 0

Views: 122

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

There's nothing "cached" about that selector, the naming is completely false.

In the "raw" version, they have:

$('#robot-arm').html('foo');

which will get optimized to

$(document.getElementById("robot-arm")).html('foo');

But the "cached" version has:

$div = $('#container');

then

$div.find('#robot-arm').html('foo');

That can't be optimized to a document.getElementById call, because the search is scoped to the #container element. But getElementById is the single fastest way to get an element from the DOM. So of course it's slower, markedly so.

A "cached" version would look like this:

var $div = $("#robot-arm");

and then

$div.html('foo');

And that is (marginally) faster than the "raw" version of the test: http://jsperf.com/using-id-selector-with-or-without-cached-scope/4

Upvotes: 2

Related Questions