1

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.

3
  • Could you show the code that you're using currently? Commented Apr 21, 2014 at 14:48
  • 1
    Are 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. Commented Apr 21, 2014 at 14:49
  • 1
    Check stackoverflow.com/a/112185/263989 Commented Apr 21, 2014 at 14:53

1 Answer 1

-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.

Sign up to request clarification or add additional context in comments.

4 Comments

Why do you tell him not to listen to people but then point to dust and handlebars?
The 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.
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.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.