Is it faster to construct jQuery objects using method syntax or pure html?
Using jQuery what provides for faster object construction:
With the HTML code
$('<dd class="foo baz" id="bar"> foobar </dd>')
Or with the pure object/method variant
$('</dd>').a开发者_StackOverflowddClass('foo').addClass('baz').id('bar').text('foobar')
I'm not sure how the internals work, feel free to supply a high level summary.
The HTML approach is surely faster, since it can utilize the browser's built-in innerHTML functionality. It's also less method calls. A 3rd approach is preferable to your 2nd, although I'd say the first is still the fastest:
$('<dd/>', {
'class': "foo baz",
id: "bar",
text: "foobar"
});
(class is in quotes since its a reserved word) The difference isn't going to be much though. I'd stick with this 3rd way unless I had a real performance problem, which is only likely if you were doing a ton of this.
I would post rather a speculation about comparison of the both. Imagine jquery can optimize the creation of html tags with all the properties their self there is only one language parsing. Much of the functionality is abstracted as to how a node is actually constructed, which can be optimized. I would also think if jquery happens to make its way into ecma script specs and all browsers start to implement it in their native code. Then your first method will be much faster.
But in the second approach you pretty much fix the approach $('</dd>').addClass('foo').addClass('baz').id('bar').text('foobar')
as to how a node gets created. Which can lead to optimization in each of those methods addClass(s), id(s), text(s)
but all of which are chained operation more of an object oriented thing and has its own overhead.
I guess jquery has to do the same language parsing for
$('<div/>')
and $('<div id='ss' />')
. So whats the difference, I don't see any!
One way is to get rid of language parsing altogether like document.createElement("div");
if you can force jquery to create node just from name 'div'
it wont require parsing which will be faster. I believe you can build a jquery extension which does this.
In current situation jquery being a javascript library the first method will require more complex string parsing so it might be slower. Methods addClass(s), id(s), text(s)
will directly translate to native DOM creation functions which will be faster.
精彩评论