7

In Firefox, I am inserting text into ~500 DIVs using this code:

$(".divs").text("default"); // ~500 DIVs

On my computer, this consistently takes 9ms if the DIVs are empty. However, this same code consistently takes 18ms if the DIVs already contain text.

Why is it that an empty DIV is 2x faster at inserting text (does jQuery need to empty the DIV first)? And, is there any way to improve the performance of replacing text in a DIV that already contains text?

Note: In IE 7, the speed differences were not as dramatic. Inserting text in an empty DIV was about 1.5x faster.

6
  • 3
    You are chasing down a 9ms performance difference? And it goes without saying, if you really want it to be fast, you would do it with plain old JS. Libraries make developing easier, but rarely offer performance increases over using vanilla code.
    – ken
    Jan 19, 2011 at 17:52
  • 4
    Yes. I'm chasing down a 2x performance difference. Jan 19, 2011 at 17:53
  • 6
    As an academic exercise, I think that this is a good question, but for your use-case I think you are well past the point of diminishing returns. No user will ever notice a 9ms difference; for that matter, no user would ever notice a 90ms difference.
    – ken
    Jan 19, 2011 at 17:56
  • p.s. it might be worth filing a bug report at bugs.jquery.com; this does seem like strange behavior. Or, you could use the debugger of a modern browser to step through the code for an empty element, and then one for an element with preexisting text, and see how the codepaths differ (and possibly gain insight into why it is slower and/or what you could do to improve it).
    – ken
    Jan 19, 2011 at 18:06
  • @ken Posting a bug sounds like a good idea - I'll do that. And, I'll see what I can find through FireBug. I'll keep this post updated with what I find. Jan 19, 2011 at 18:14

5 Answers 5

6
+50

If you want the fastest solution for all browsers use textContent if supported and fallback to innerText / innerHTML otherwise [Test] (knowing the gotchas).

/**
 * Replaces text for all elements in the given array.
 * @param {Array} elems
 * @param {String} text
 */
var replaceText = (function(){
  var dummy = document.createElement("div");
  dummy.innerHTML = "text";
  var TEXT = (dummy.textContent === 'text') ? 'textContent' : 'innerText';
  return function(elems, text) {
    for (var i = elems.length; i--;) {
      elems[i][TEXT] = text;
    } 
  };
})();

Faster than jQuery text:

  • 4x on IE 8
  • 2.2x on Firefox 4b11
  • 1.3x on Chrome
0
6

If the text you are inserting does NOT need to be escaped, then you might want to try the following:

$(".div").each(function(){
  this.innerHTML = "default";
});

jQuery does some processing to the text when you use the method .text().

We need to be aware that this method escapes the string provided as necessary so that it will render correctly in HTML. To do so, it calls the DOM method .createTextNode(), which replaces special characters with their HTML entity equivalents (such as < for <).

Edit To avoid the penalty of the .each() method you can try the following:

var divs = $(".divs"),
    i = 0,
    len = divs.length;
while(len--) {
  divs[len].innerHTML = "default";
}

If that doesn't get you any performance gains then it's definitely a browser implementation issue. At least that would rule out jQuery performance issues/bugs.

7
  • Thanks for the help. 1) This actually takes longer due to the .each() loop and 2) The code is still faster when the DIVs are empty. Jan 20, 2011 at 17:27
  • It might a browser implementation issue then! you know having to release the memory of those strings. just a guess. Have you tried different browsers?
    – Marco M.
    Jan 20, 2011 at 17:54
  • 1
    How strange is this - the pure vanilla for loop is slower than the $(".divs").text("default") in FF and IE (using exact code above). In fact, in IE, it's about 5x slower. Perhaps it is a browser implementation issue of releasing resources. Strange stuff ... Thanks for the help though. Jan 20, 2011 at 19:25
  • mhmm hope my edit well be published on this. if not: for-loops aint that fast ( 1 comparison + 1 increment + the stuff to do) ... using while(len--) should be way faster (except for IE7) Feb 8, 2011 at 22:11
  • @david I don't know how while(len--) could be way faster? you're still doing 1 comparison 1 decrement. while and for loops are supposed to be syntactic sugar for the same thing.
    – Marco M.
    Feb 10, 2011 at 15:54
4

You can gain performance by reusing an existing text node.

A DIV element that contains only text, is a DOM element that contains one child node whose type is a text node. The text content is stored within this text node, and not within its parent DIV element.

The main problem with methods such as .text() in JQuery, or .innerHTML() in HTML DOM, or even .innerText() and .textContent(), is that they all create a new text node (even if one exists already). More specifically, all methods listed above start by removing all DOM child nodes, including an eventually pre-existing text node (this is also done by the implementations of innerHTML, innerText and textContent). This leaves the context element (the DIV, in your case) empty, without any children at all. They then create a new child node of type text node, assigning the new text to it, and appending it to the context element. innerHTML furthermore attempts to parse the input HTML string and constructs a DOM fragment out of it.

The fastest method that I know for replacing an existing text node is as follows:

var divs = $(".divs").get(),  
     len = divs.length;  
while(--len) {  
  divs[len].firstChild.data = "default";  
}

This method does not create a new child node, but merely replaces the text of the existing text node. Obviously, this method assumes that the text node exists already. For this to work, your initial document may be initialized with any non-empty text inside the DIVs (and excluding any other child elements).

3

Yes, the reason for this method to be slower when elements have child elements is because jQuery's .text() method first runs the .empty() method and then .append(document.createTextNode(text))

From jQuery.text

// ...
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
// ...

The reason I'm pointing out this is that .empty() method calls .cleanData() method that removes any data and/or events associated with its child nodes, and then, does a standard .removeChild() method on all its child nodes to remove them, which is the main reason why divs that already contain text are slower to update.

The solution to your problem, is to write your own, vanilla, javaScript functions for updating the text of your divs, but make sure you're not attaching any click events or data to them via jQuery, since you will most definitely have some memory leaks.

1

If you don't need to escape html tags (ie replacing <a> with &lt;a&gt;) then .html might be faster. Also yes it does need to empty the divs before replacing it with the new content.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.