Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is innerHTML = "" slow in Firefox

I am testing the speed of different methods to dynamically add html elements to the DOM. I've build a tester here (code is working version, so pretty sloppy). The results are (very) different for different browsers with Chrome getting all the points for speed, and Opera a good second - but that's not the question here.

In Firefox I detected a problem with clearing a div (from it's childNodes). When some 50.000 div elements are added, it takes ages to clear, using just

[div].innerHTML = "";

What is going on here? Did firefox implement some intrinsic garbage collection method for this?

like image 625
KooiInc Avatar asked Mar 04 '09 08:03

KooiInc


People also ask

Why is innerHTML slow?

innerHTML is slow because it has to look for HTML tags in the value, and parse it into DOM nodes. If you're just inserting plain text that doesn't contain any HTML tags, use textContent instead.

Why you shouldn't use innerHTML?

The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies.

Is innerHTML fast?

html is the fastest, followed by . append . followed by . innerHTML .

Is setting innerHTML synchronous?

Setting innerHTML is synchronous, as are most changes you can make to the DOM.


1 Answers

While I am not sure about the innerHTML = "" you left out one possibly fast appoach using DocumentFragments for inserting into the DOM: As John Resig shows.

As Ólafur Waage already mentioned, even though innerHTML is faster in a lot of situations since it's not part of any W3C standard, quirks are far more likely to be introduced then if they were. Not to say innerHTML is not a defacto standard within modern browsers.

This blog post seems to indicate that Firefox spends a lot of time cleaning up after itself when using innerHTML to remove elements.

In some browsers (most notably, Firefox), although innerHTML is generally much faster than DOM methods, it spends a disproportionate amount of time clearing out existing elements vs. creating new ones. Knowing this, we can combine the speed of destroying elements by removing their parent using the standard DOM methods with creating new elements using innerHTML.

like image 102
Martijn Laarman Avatar answered Nov 15 '22 06:11

Martijn Laarman