Element Creation

JavaScript performance comparison

Revision 3 of this test case created

Info

Compare various methods of creating DOM elements.

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<style>
  .hidden { display: none; }
</style>
<div class="hidden" id="container">
</div>
<script>
Benchmark.prototype.setup = function() {
    var container = document.getElementById('container'),
        _ = {},
        $ = {};
   
    'table,tbody,tr,td'.split(',').forEach(function(tag) {
      var basis = {};
      var f = function(attrs) {
          var el = basis[tag].cloneNode(false);
          if (attrs) {
            Object.keys(attrs).forEach(function(it) {
              el.setAttribute(it, attrs[it]);
            });
          }
          for (var i = 1; i < arguments.length; i++) {
            el.appendChild(arguments[i]);
          }
          return el;
          };
      basis[tag] = document.createElement(tag);
      _[tag] = f;
    });
   
    _.text = function(content) {
      return document.createTextNode(content);
    };
   
    'table,tbody,tr,td'.split(',').forEach(function(tag) {
      var f = function(attrs) {
          var el = arguments.callee.basis.cloneNode(false);
          if (attrs) {
            Object.keys(attrs).forEach(function(it) {
              el.setAttribute(it, attrs[it]);
            });
          }
          for (var i = 1; i < arguments.length; i++) {
            el.appendChild(arguments[i]);
          }
          return el;
          };
      f.basis = document.createElement(tag);
      $[tag] = f;
    });
   
    function buildera() {
      var t = _.table(undefined);
    }
   
    function builderb() {
      var t = $.table(undefined);
    }
   
    function html() {
      container.innerHTML = '<table></table>';
    }
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
A
buildera();
pending…
B
builderb();
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:

0 comments

Add a comment