Javascript – Performance Issue – Creating New Elements

I was messing around a jQuery Mobile Project. when I started worrying about performance on the mobile webkit browsers in creating a very long view, although my list size won’t reach a critical point to worry about performance, yet I was curious to know which is the fastest method to create new elements in JS.
There is two main methods either using the standard document method


var e = document.createElement('div');

or using the sexy JQuery wrapper $ in either of the following three ways


var e = $('<div>');       // Method 1

var e = $('<div/>')       // Method 2

var e = $('<div></div>'); // Method 3

Any of the previous methods will work but of course don’t try to ommit the <> tags like this


var e = $('div');

as this will result in e having an array of all div tags within the document, however this makes us raise a very important question about the difference between the two methods, I did a simple benchmark test with 50,000 elements and this was the result

Method Time for 50,000 elements
$ Method 1 ~ 300 ms
$ Method 2 ~ 320 ms
$ Method 3 ~ 300 ms
createElement(‘div’) ~ 42 ms

a significant difference appears in run time I concluded that the reason might be in the regular expresson search that the JQuery Wrapper method works on a given string to indicate the purpose of the method call weather it is a call for cloning an existing element or a conditional nested query for a specific element or to just create a new element like in our case then it calls the createElment method normally

I inspected then the jQuery Source code and find it like I thought it was that’s a screenshot from the part of the source code where it checks if the match of the regex is for creating a new tag.

Advertisements

One thought on “Javascript – Performance Issue – Creating New Elements

  1. You can enhance it even more using:
    1- var c = document.createElement;
    2- var d = ‘div’;
    3- In the loop, do ==> c(d);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: