For what I want to accomplish, I can use either createElement()
or innerHTML
and a string.
Which is truly faster in the end? I've been led to believe for a long time that strings are much slower than built-in functions that return the same results, but is it really true?
I ask because I've tried createElement()
and it seems that all of the properties that have to be added to each element slows things down. Not only that, but it takes up more space, too. I have a loop that goes anywhere from 1-infinity based on an array's length, though preferably adding up to 50 or so elements before showing signs of slowing down. Within these 50 or so elements that I wish to create are about 10 more elements. So, in all, it's actually creating around 500 elements.
I noticed a bit of a slowdown faster than usual by creating elements with the built-in functions, and due to my fooling around resetting that array (the array was 5D and not set in the same script), I'd like to know which is truly better, both as far as speed goes and simply the better practice, before doing it all over.
In an HTML document, the document.createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.
The document. createElement() creates a new HTML element. The element. appendChild() appends an HTML element to an existing element.
Performance differences for this issue vary between browsers, and (sometimes) between different versions of any one browser, and I've seen a few different articles giving different advice on this issue.
In my own experience, I only recall one time that I really needed to make large changes to a big web page, specifically rebuilding a table element that had hundreds or potentially thousands of rows each of which had lots of cells, and I found that building up a string variable and then setting innerHTML once at the end was much, much faster than trying to do it through the DOM functions. But, this was for a particular intranet web app where it was guaranteed that 100% of the users would be on IE so I didn't need to worry about cross-browser testing.
Even if you decide to go the string-building route, there are different opinions about how to speed that up. I've read more than one article that compared the performance of continuously adding to the end of your string (standard myString += 'something' + 'something else'
type operations) against appending to the end of an array variable and then using Array.join() to create one big string at the end. Again this made a big difference for certain versions of some browsers but was no different or worse in others.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With