EntropySink

Technical & Scientific => Programming => Topic started by: Mike on December 18, 2011, 06:06:12 PM

Title: jQuery element creation benchmark
Post by: Mike on December 18, 2011, 06:06:12 PM
On the SMF forums someone linked to an article saying that $('<div>') was slower than document.createElement('div').  Decided to benchmark it.
Method 1: $('<div>')
Method 2: $('<div></div>')
Method 3: $('<div />')
Method 4: document.createElement('div')
Method 5: $(document.createElement('div'))

The difference between #4 and #5 is that #5 creates a jQuery object like #1-#3 while #4 doesn't.  So it is a "more equal" test.

Results for 10,000 iterations:
#1: 61 ms
#2: 51 ms
#3: 34 ms
#4: 10 ms
#5: 14 ms

Recommendation:  Seriously, we are talking about 47 ms for 10,000 iterations.  You are liable to hit a CPU or network lag spike that lasts that long.

That said, no reason not to use $('<div />') over $('<div>')
Title: Re: jQuery element creation benchmark
Post by: micah on December 19, 2011, 08:09:30 AM
nice! I agree!

That said, I've seen several articles that point out how "slow" the selector is, especially when you have to parse through every iteration of a common HTML element. like $('p') or, as you stated $('div').  Yeah, its not a lot, but if you're not cacheing the object, it can make a difference and there's no reason not to program efficiently.

I just googled this again, and one of the first results was this blog with some good best practice tips: http://www.artzstudio.com/2009/04/jquery-performance-rules/