xms
xms

Reputation: 437

jQuery and speed of .replaceWith() vs. .html()

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

Answers (3)

Rion Williams
Rion Williams

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/second
  • html() - averaged 58,446 operations/second

These tests were run using jsPerf and can be seen here and demonstrated below:

enter image description here

Upvotes: 2

ruler23
ruler23

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

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

B) would be quicker, as it directly invokes innerHTML.

A) would go to the parent element and call replaceChild.

https://github.com/jquery/jquery/blob/56136897f241db22560b58c3518578ca1453d5c7/src/manipulation.js#L451

Upvotes: 0

Related Questions