By Uzi Refaeli
October 31st, 2005
innerHTML Vs. createElement
In some applications, there is a need to manipulate the
DOM (Document Object Model) and insert new elements into the document (remember that most chances are you will make your application
less accessible!).
There are 2 main methods for doing so using innerHTML and createElement/appendChild methods.
In order to check which method will provide the best performance based results I have created a simple test, 100x100 matrix which was implemented as a table.
I made 3 different tests:
innerHTML using array.join (see JavaScript Performance Issues - Lesson 1).
createElement I - creating the end elements before appending them into their parents. (see code for more information)
createElement II - Each created element is being appended into its parent immediately. (see code for more information)
The tests were performed with three different browsers, IE6, FF1.5B1 (FireFox 1.5 Beta 1) and Opera 8.5.
Here are the results:
| Method |
Browser |
Average |
innerHTML |
IE 6 |
385ms |
| FF 1.5B1 |
396ms |
| Opera 8.5 |
125ms |
createElement I |
IE 6 |
3093ms |
| FF 1.5B1 |
1219ms |
| Opera 8.5 |
536ms |
createElement II |
IE 6 |
1661ms |
| FF 1.5B1 |
1989ms |
| Opera 8.5 |
1453ms |
The results show that innerHTML is much faster than both createElement methods of work.
We can also learn something interesting about the different browsers handling of DOM manipulation.
IE shows the best results when rendering each element immediately and when an object is appended to an already rendered parent element.
FireFox and Opera preformed better when they collected all the elements and only than rendered them into the DOM.
cloneNode Vs. createElement
In all browsers creating massive elements using createElement show better results than cloneNode(true).
In IE and Opera browsers cloneNode show better results than createElement while cloning with deep=false (cloning the element itself without its child).
In this case FireFox shows the same average runtime.
Use both methods according to the required context in order to achieve the best performance.
Conclusion
Following the above guidelines can improve the performance of your code and provide the end user a better and smoother experience.