I have some Javascript that it dynamically creating some Javascript. Part of this is concatenating several thousand strings together, which is quite slow. What is the fastest way to build HTML dynamically in Javascript based upon a Json object.
Asked
Active
Viewed 2,834 times
1
-
Could you show the code that you're using currently? – Pavlo Apr 21 '14 at 14:48
-
1Are you looking to improve concatenation or writing to the DOM? There isn't really any option to concatenate faster – afaik – than `+`. But there are tricks for working with the DOM. – Ingo Bürk Apr 21 '14 at 14:49
-
1Check http://stackoverflow.com/a/112185/263989 – fasouto Apr 21 '14 at 14:53
1 Answers
-1
If you want to build HTML out of a JSON object, a templating engine is what you need.
There are several out there, but make your choice based on your requirements, not on what people tell you is "the best".
If there's the possibility that you have to do asynchronous calls in the render process, you definitely should go for an asynchronous templating engine.
dust.js is one of those.
For sync use only, handlebars is a popular choice. It's quite fast, but it is intended to be very minimalistic. Meaning, the logic should mostly happen outside of the templates.
Maybe have a look at http://garann.github.io/template-chooser/ and pick one that suits your needs.

Tim
- 2,430
- 19
- 20
-
Why do you tell him not to listen to people but then point to dust and handlebars? – Bergi Apr 21 '14 at 15:23
-
1The question was "*how to do string concatenation fast?*". Surely, templating engines have to deal with this problem, but the proper answer would be to explain *how* they solve it. – Bergi Apr 21 '14 at 15:25
-
I told him not to listen to people telling him what is the best, since it depends on the use case. Then I gave him an example of an async templating engine and one that's sync to contrast both a bit, and a link to a tool that allows you to pick. I assume that should be enough to make a decision by himself. – Tim Apr 21 '14 at 15:27
-
@Bergi The question was "What is the fastest way to build HTML dynamically in Javascript based upon a Json object." In that case, using an already existing templating engine seems to be the best advice. If you care about how they accomplish it, that's beyond the scope of this question. There are plenty of articles available, and even source code, that show how it works. But there is no single easy answer. And if it's just about what's the fastest way to concatenate strings in JS, there are plenty of SO posts for that already. – Tim Apr 21 '14 at 15:31