Author Topic: jQuery element creation benchmark  (Read 1479 times)

Mike

  • Jackass In Charge
  • Posts: 11248
  • Karma: +168/-32
  • Ex Asshole - a better and more caring person.
jQuery element creation benchmark
« 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>')

micah

  • A real person, on the Internet.
  • Ass Wipe
  • Posts: 6915
  • Karma: +58/-55
  • Truth cannot contradict truth.
    • micahj.com
Re: jQuery element creation benchmark
« Reply #1 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/
"I possess a device, in my pocket, that is capable of accessing the entirety of information known to man.  I use it to look at pictures of cats and get in arguments with strangers."