8

today i learned that adding to innerhtml using a loop is so much slower than adding to a variable and writing it once.

sometimes i wonder if i were happier as a professional programmer. and then i experience this which means my family would be living under a bridge in no time.

Comments
  • 5
    Any direct modification to the DOM is slower than if its done in memory and added as one transaction to it.

    The reason for this the DOM will be rerendered on every change and all boxes have to be recalculated.
  • 1
    You don't modify the DOM that frequently

    What you ended up with is like doing calculations in a worker thread and then passing the result to the main UI thread
  • 1
    @asgs thats true, I just didnt want to extend it to threads for a simple explanation.
  • 3
    To expand on that: when you fumble with the innerHTML, the browser does a complete re-layout of that block. This also implies that e.g. ongoing CSS transitions in this block are cancelled. This doesn't happen if you use appendChild.

    Obviously, still via creating a document fragment, appending to that in the loop, and then finally appending the fragment via appendChild.

    Besides, mucking with innerHTML should only be done if you have strict control over the injected data. Otherwise, it might become a security issue.
  • 2
    thanks for the explanations!
    i guess i might have understand that earlier but the content showed up completely after some seconds so it was not obvious for me that it had to recalculate repeatedly.
    @Fast-Nop although in this scenario i have complete control over the content i try to remember for the next use case!
  • 3
    @erroronline1 for smaller pages its rarely visible but as everything builds up it become a real issue.
  • 1
    @Codex404 on a side note, threads are simple to explain, too. Especially when we are taking about UI and DOM
  • 2
    @asgs sure but not actually needed to explain it. Using terms like threads may scare people who dont know that and the chance is relatively big that someone who only does developing as hobby and does not know basic things of the DOM don't know about threads.

    It also is not how it works in every browser. Netscape navigator, firefox and chrome all work different when looking at threads so the explanation would have to be a lot bigger than the few words I used.

    Yes you are correct but I think it will be less clear when you still want to be fully correct.
  • 1
    @Codex404 well, for somebody wondering why it took some time to render the data, bringing up the threads is the right direction to start debugging on.

    But let's agree to disagree
  • 0
    And so the virtual Dom was born
  • 1
    @Minion in the shadows of Moria, react-ing to a deja-vue - depending on from what angle you look at it.
Add Comment