Performance Comparison: document.createElement('img') vs. new Image()

When I was working on a script to preload images with JavaScript one of the decisions I had to make was whether to use document.createElement('img') or an image object to preload the image into. The recommended w3c method is to use document.createElement('img') as it is a consistent way to create elements. This is the method I used. But, I was wondering which performed better. So, I ran some tests and here is what I learned.

Test Setup

There are numerous browsers on the web. Testing in Firefox and Safari, which is where I do most of my development, isn't enough. Internet Explorer is the dominant browser and there are still as many IE6 users are there are Firefox users. I wanted to know how this would perform for real world users so I tested Firefox 3.5, Safari, Webkit Head, and Internet Explorer 6, 7, and 8.

The goal isn't to get an absolute performance measurement but to see which is the faster of the two methods. The basic script I used was:

(function() {
  var TestImage = '/image.png';
  var start;
  var end;
  var timediff;

  preLoadImages1 = function() {
    start = new Date();
    for (var i = 10000; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = TestImage;
    }
    end = new Date();
    timediff = end - start;
    alert(timediff + 'ms  ');
  }

  preLoadImages2 = function() {
    start = new Date();
    for (var i = 10000; i--;) {
      var cacheImage = new Image();
      cacheImage.src = TestImage;
    }
    end = new Date();
    timediff = end - start;
    alert(timediff + 'ms  ');
  }
  preLoadImages1();
  preLoadImages2();
})()

The Results

In Firefox 3.5, Safari, and Webkit head there was not noticeable difference between the two methods. When I ran the test numerous times there was no consistent winner.

Internet Explorer was a different. In Internet Explorer 6 and 7 using new Image() performed about 8% better and 10% better on average. Internet Explorer 8 was a different story. Using document.createElement('img') performed about 20% faster.

For now I'm going to continue to use document.createElement('img'). Not only is this the w3c recommendation but it's the faster method in IE8, the version users are slowly starting to adopt.