Reputation:
I have a div that is not contentEditable. I capture keystrokes, insert the associated char into a string in memory, and then call a render() function that replaces the innerHTML of the div with the current string.
My question is, why does this loop get slower and slower as the innerHTML get's larger? All I'm doing is overwriting the innerHTML of the div with a straight string. Shouldn't this be constant time?
dojo.byId('thisFrame').innerHTML = this.value.string;
I don't understand how this is dependent on the size of the string at all. It slows down when the string's length gets over about 200 characters, and slows down drastically from there on out.
Upvotes: 3
Views: 1720
Reputation: 2082
The html you set using innerhtml must be parsed by the browser in order to get the DOM elements that make up the browsers internal representation of the div. This takes more time for a longer string with a greater number of elements.
Upvotes: 3
Reputation: 120576
dojo.byId('thisFrame')
is a DOM element. Setting the innerHTML
property of a DOm element is not constant time because it causes a side effect which does not take constant time.
Specifically, assigning to myHTMLElement.innerHTML
causes the browser to parse the string with its HTML parser and rewrite a chunk of the DOM.
http://www.w3.org/TR/2008/WD-html5-20080610/dom.html#innerhtml0
On setting, [innerHTML] replaces the node's children with new nodes that result from parsing the given value.
Parsing HTML is at least linear in the amount of HTML, and replacing the DOM is at least linear in both the number of nodes removed and the number of nodes added.
Upvotes: 6