1

Typically, when I sort a table in the DOM, I create a data array that mirrors the table elements, capturing the information that's meaningful to me (including any attributes that are relevant) in JS objects. At this point, after determining the proper sort, I have two choices:

  1. Rewrite the data in the table (using innerHTML, textContent, etc.), iterating over all the table elements.
  2. Reorder the table row element (i.e. HTML nodes) to reflect the proper order in the sorted array.

Which method is less costly (i.e. faster)? I assume it's the latter, but I'm not sure. Can you explain why a particular method is faster?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Son of the Wai-Pan
  • 12,371
  • 16
  • 46
  • 55
  • This is usually a tough to predict because while the second obviosly should be faster, it however constantly crosses the JS/Native API boundary which is costly. The innerHTML way however invokes expensive parser and a full rebuild of a tree, however, there is no boundary crossing during this (obviously you will build the whole string in JS before passing it and just setting innerHTML **once**). – Esailija Aug 11 '13 at 12:52
  • benchmark? maybe? It probably depends on the browser too. – Dave Aug 11 '13 at 13:02
  • 1
    Try it: http://jsperf.com/. – Felix Kling Aug 11 '13 at 13:12
  • By "*rewriting the data*" you mean "… of each `` cell"? – Bergi Aug 11 '13 at 15:53
  • 1
    Yes. I mean accessing the particular HTML Element and doing a .textContent = "blah" on i. – Son of the Wai-Pan Aug 12 '13 at 05:24

0 Answers0