Frage

Is there any point in caching a Converter object? How expensive is it to construct? Or can I just do this?

function convertMarkdown(str) {
    var converter = new Markdown.Converter();
    return converter.makeHtml(str);
}
War es hilfreich?

Lösung

The converter object is fairly cheap to construct. There's usually no major initialization going on. A quick'n'dirty measurement on my (reasonably beefy) machine: To create one million converter objects,

  • Chrome needs 8 seconds (5x)
  • Opera needs 14 seconds (10x)
  • IE needs 4 seconds (3x)
  • Safari 5 needs 2.5 seconds (5x)
  • Firefox needs 44 seconds (20x)

So even in the slowest case, that's just 44µs per object. The number in parentheses means "How much slower is this roughly, compared to constructing new Date() instead?"

So I'm going to say that in most cases this won't be your bottleneck, and if you're only converting Markdown once in a while, it won't make a practical difference.

Compare to the actual cost of using the converter object. Creating a single converter object, and then measuring how long it takes to process the string "Hello" (note that this string doesn't even contain any formatting) a million times,

  • Chrome needs 13 seconds
  • Opera needs 86 seconds
  • IE needs 17 seconds
  • Safari 5 needs 25 seconds
  • Firefox needs 200 seconds

To process some "real" Markdown data – the content of this very answer – one million times, Chrome needs on the order of 800 seconds (I didn't measure this in other browsers). So in real-world use, the converter construction time isn't very relevant to the overall performance.

Unless you're really only calling it once or twice, I personally would cache the object anyway, just because I think it's more readable.

Compare

var s = new Markdown.Converter().makeHtml(src);

vs.

var s = myConverter.makeHtml(src);

or (using Andreas' answer)

var s = convertMarkdown(src);

– when skimming over that code in a larger context, the first version needs a second glance to notice that the creation of the object is just secondary to the purpose of the line.

And if you're registering plugins on the converter object, the creation even takes multiple statements, making the case even better for creating the object just once.

Andere Tipps

It depends on the Markdown.Converter function and how often you will call it, but you can easily create a function that holds a reference to the converter instance so it dont need to recreated with every call:

var convertMarkdown = (function{
    var converter = new Markdown.Converter();
    return function(str){
      return converter.makeHtml(str);
    }
})()
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top