Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to improve performance of inserting text into an HTML element?

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.

like image 250
Stephen Watkins Avatar asked Jan 19 '11 17:01

Stephen Watkins


1 Answers

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
like image 97
25 revs, 4 users 83% Avatar answered Sep 23 '22 02:09

25 revs, 4 users 83%