views:

26294

answers:

8

Hi guys,

Recently I've been doing a lot of modal window pop ups and what not, for which I used jQuery. The method that I used to create the new elements on the page has overwhelmingly been along the lines of:

$("<div></div>");

However, I'm getting the niggling feeling that this isn't the best or the most efficient method of doing this. What is the best way to create elements in jQuery from a performance perspective?

Cheers

+3  A: 

I think you're using the best method, though you could optimize it to:

 $("<div/>");
tvanfosson
+26  A: 

personally i'd suggest (for readability):

$('<div>');

some numbers on the suggestions so far (safari 3.2.1 / mac os x):

var it = 50000;

var start = new Date().getTime();
for (i = 0; i < it; ++i)  {
  // test creation of an element 
  // see below statements
}
var end = new Date().getTime();
alert( end - start );                

var e = $( document.createElement('div') );  // ~300ms
var e = $('<div>');                          // ~3100ms
var e = $('<div></div>');                    // ~3200ms
var e = $('<div/>');                         // ~3500ms
Owen
From the jquery docs: 'When creating single elements use the closing tag or XHTML format. For example, to create a span use $("<span/>") or $("<span></span>") instead of without the closing slash/tag.'
tvanfosson
i assumed that was outdated, as the method i describe creates just as valid XHTML. ex: var e = $('<div>').append($('<div>')).html();alert(e); is there some other metric that would render this method unfavourable to use?
Owen
@Owen, that behavior is a bug, not a feature. Garbage in, garbage out -- it just so happens that the garbage you get is acceptable. Don't rely on it between jQuery versions, though, unless the specification for the function changes.
strager
As expected, seeing similar numbers in Mac OS X Chrome (100ms for createElement() vs. 500ms text parsing) and Mac OS X Firefox (350ms vs. 1000ms). Thanks for writing up the test loop.
Adam Backstrom
+29  A: 

I use $(document.createElement('div')); Seems fastest to me because jQuery doesn't have to identify it as an element and create the element itself.

You should really run benchmarks with different Javascript engines and weigh your audience with the results. Make a decision from there.

strager
jQuery "appends" it to DOM? Where? This doesn't make much sense to me -- where would the div go?
strager
a created div in jquery has to be added just like in javascript. $('<div>') by itself isn't attached to the DOM until you append() it to something.
Owen
omg, great advice! Thanks alot!
Ionut Staicu
@tvanfosson: Sorry buddy, you are wrong again. If you want that `$(document.createElement('div'))` part added to the DOM you will have to append or prepend it to another element (already in the DOM). As it is, the element jquery creates is NOT attached to anything (at least in modern browsers that support documentFragment, AFAIK).
David Murdoch
@David - obviously you're right. I will note that I added the comment about 2 years ago just when I was starting to learn jQuery. You would need to do an `appendTo`, ... Because the comments were obviously wrong, I've removed them.
tvanfosson
+1  A: 

You don't need raw performance from an operation you will perform extremely infrequently from the point of view of the CPU.

Justice
Depends on how frequently you are doing it.
Rich Bradshaw
The OP is creating a *modal popup*. This operation is not repeated thousands of times per second. Instead, it is repeated maybe once every few seconds, at maximum. Using the `jQuery(html :: String)` method is perfectly fine. Unless the situation is extremely unusual, one will be unlikely to achieve better *perceived* performance. Spend the optimization energy on the cases that could use it.Additionally, jQuery is optimized for speed in many ways. Do sane things with it, and trust-but-verify it to be fast.
Justice
+4  A: 

If you have a lot of HTML content (more than just a single div), you might consider building the HTML into the page within a hidden container, then updating it and making it visible when needed. This way, a large portion of your markup can be pre-parsed by the browser and avoid getting bogged down by JavaScript when called. Hope this helps!

Collin Allen
Thanks for the advice. I have used this approach before, however in this particular case I am specifically wanting to know about creating elements.
Darko Z
+4  A: 

This is not the correct answer for the question but still I would like to share this...

Using just document.createElement('div') and skipping JQuery will improve the performance alot when you want to make lot of elements on the fly and append to DOM.

Irshad
+4  A: 

Actually, if you're doing $('<div>'), jQuery will also use document.createElement().

(Just take a look at http://code.jquery.com/jquery-1.4.2.js, line 117).

There is some function-call overhead, but unless performance is critical (you're creating hundreds [thousands] of elements), there isn't much reason to revert to plain DOM.

Just creating elements for a new webpage is probably a case in which you'll best stick to the jQuery way of doing things.

edwin
A: 

One point is that it may be easier to do:

$("<div class=foo id=bar style='color:white;bgcolor:blue;font-size:12pt'></div>")

Then to do all of that with jquery calls.

Tobiah
4 spaces in front of a line makes it format like code. Select a block and hit `Ctr-k` go achieve this.
Peter Ajtai