Performance Comparison Between createElement and innerHtml: createelement

Source: Internet
Author: User

Performance Comparison Between createElement and innerHtml: createelement

In js, there are roughly two ways to add html dynamically. One is to create a document. createElement method, and then add it using Element. appendChild or Element. innerHTML = sHTML method. The preceding two methods are obviously more flexible. Apart from the Element. appendChild method, there are other dom operations such as insertBefore. Flexibility is not discussed here, but performance is explored.

The comparison method is simple:

Each generation generates 10000 records, as shown in <div> <span> Performance Test </span> ...... </div> html, and then put it into the body at one time, record the whole process, time consumed, and run 10 times, output time consumed.

The Code is as follows:

Window. onload = function () {testPerformance (10, function () {document. body. appendChild (generateHtmlElement (10000);}) testPerformance (10, function () {document. body. innerHTML = generateHtmlString (10000) ;})} function testPerformance (iTimes, fn) {var iLastTime = null; var iTotalTime = 0; for (var I = 1; I <= iTimes; ++ I) {iLastTime = new Date (). getTime (); fn (); var iCost = new Date (). getTime ()-iLastTime; console. log ("+ I +" Times: "+ iCost +" millisecond "); iTotalTime + = iCost; document. body. innerHTML = ""; iLastTime = new Date (). getTime ();} console. log ("Total time:" + iTotalTime + "millisecond"); console. log ("Average time:" + iTotalTime/iTimes + "millisecond");}/** use document. createElement and other dom methods to generate elements <div> <span> test performance </span> .... <div> * times: Number of generated div * return Element */function generateHtmlElement (iTimes) {var result = document. createElement ("div"); for (var I = 0; I <iTimes; ++ I) {var eDiv = document. createElement ("div"); for (var j = 0; j <10; ++ j) {var eSpan = document. createElement ("span"); eSpan. appendChild (document. createTextNode ("test performance"); eDiv. appendChild (eSpan);} result. appendChild (eDiv);} return result;}/** use String concatenation to generate <div> <span> test performance </span> .... <div> string * times: Number of generated div * return string */function generateHtmlString (iTimes) {var sb = new StringBuilder (); for (var I = 0; I <iTimes; ++ I) {sb. append ("<div>"); for (var j = 0; j <10; ++ j) {sb. append ("<span> Performance Test </span>");} sb. append ("</div>");} return sb. toString ();} function StringBuilder () {this. _ asBuilder = [];} StringBuilder. prototype. clear = function () {this. _ asBuilder = []; // this method is better than this. _ asBuilder. length = 0 a little faster, how much faster, look at the length of the array} StringBuilder. prototype. append = function () {Array. prototype. push. apply (this. _ asBuilder, arguments); // call the push method of Array, so that multiple parameters return this can be passed using append; // append (""). append () effect} StringBuilder. prototype. toString = function () {return this. _ asBuilder. join ("");}


During String concatenation, a custom StringBuilder class is used to improve the String concatenation performance.

The test results are as follows:

In chrome, the difference is not too much, and innerHTML is slightly better:


In Firefox, innerHTML completes the createElement


IE11. It should be said that IE11 was cracked by chrome and Firefox.

To sum up, in terms of performance, innerHTML is faster than the createElement creation element in the append into the dom. in IE, the difference is farther. Why are you so slow, IE ?! Is there a problem with my testing method ?!


InnerHTML and createElment are different

InnerHTML is an attribute of an element. By modifying its value, you can modify the content of an element, that is, modifying the document.
CreateElement only creates an element in the memory and is not added to the document.
The return value of createElement is the created Element Object. You can add it to the document using the appendChild method. The value assigned by innerHTML can only be a string.
In fact, the two have little to do with each other, and it makes little sense.

DocumentcreateElement (tag), where tag is the string of innerHTML. It can be normally displayed in ie, but not in firefox.

DOM elements encapsulated by jQuery objects.
You can pass a handwritten HTML string, a string created by some template engines or plug-ins, or a string loaded through AJAX. However, there are limits when you create an input element. For more information, see the second example. Of course, this string can contain a slash (such as an image address) and a backslash. When creating a single element, use the closed tag or XHTML format. For example, to create a span, you can use $ ("<span/>") or $ (""), but $ ("") is not recommended (""). In jQuery, this syntax is equivalent to $ (document. createElement ("span ")).
Parameters
HtmlString
HTML Tag string used to dynamically create DOM elements
OwnerDocument (optional) Document
Document where the DOM element is created
Example description:
Dynamically create a div element (and all its content) and append it to the body element. In this function, an element is created temporarily and the innerHTML attribute of this element is set to a given tag string to convert the tag to the DOM element. Therefore, this function has both flexibility and limitations.
JQuery code: $ ("
Hello
"). AppendTo (" body "); Description:
To create a <input> element, you must set the type attribute at the same time. Because Microsoft requires that the type of the <input> element can be written only once.
JQuery code: // invalid in IE:
$ ("<Input>"). attr ("type", "checkbox ");
// Valid in IE:
$ ("<Input type = 'checkbox'> ");
Favorites

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.