Element Creation

JavaScript performance comparison

Revision 4 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'),
        _ = {},
        $ = {},
        basis = {};
   
    function tag_ctor(tag) {
      basis[tag] = document.createElement(tag);
      _[tag] = 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;
      };
      return _[tag];
    }
   
    // 'table,tbody,tr,td'.split( ',' ).forEach( function ( tag ) {
    //  tag_ctor( tag );
    // });
    _.text = function(content) {
      return document.createTextNode(content);
    };
   
    _.__noSuchMethod__ = function(id, args) {
      var f = tag_ctor(id);
      return f.apply(window, args);
    };
   
    'table,tbody,tr,td'.split(',').forEach(function(tag) {
      var f = function(attrs) {
          var el = document.createElement(tag);
          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;
          };
      $[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