Reputation: 437
I have a simple HTML code:
<div class="inner"><h2>Old heading</h2></div>
Which one is faster, A) or B)?
A)
$( 'div.inner' ).replaceWith( '<div class="inner"><h2>New heading</h2></div>' );
B)
$( "div.inner" ).html( "<h2>New heading</h2>" );
Is there even faster ways available?
Upvotes: 1
Views: 1269
Reputation: 76557
Using html()
is going to be significantly faster than using the replaceWith()
function, roughly twice as fast (~57% when ran locally). This can be expected as at it core, it's just a wrapper for setting the innerHtml
property of an element.
The Numbers
replaceWith()
- averaged 24,767 operations/secondhtml()
- averaged 58,446 operations/secondThese tests were run using jsPerf and can be seen here and demonstrated below:
Upvotes: 2
Reputation: 49
Here's a test case I prepared for you
https://jsperf.com/jqueryroller
The results (on my PC) show that html() is about 2x times faster than replaceWith().
You can use jsperf to test similar things in the future and even edit my tests if you need to.
Upvotes: 0
Reputation: 34895
B) would be quicker, as it directly invokes innerHTML
.
A) would go to the parent element and call replaceChild
.
Upvotes: 0