Antaris / RazorEngine

Open source templating engine based on Microsoft's Razor parsing engine
http://antaris.github.io/RazorEngine
Other
2.14k stars 578 forks source link

How to improve efficiency in compiling razor templates? #549

Open bnuzhouwei opened 5 years ago

bnuzhouwei commented 5 years ago

The RunCompile cost much time on the first runs, and the second time is much faster: i.e. I run a template on Rasp PI 3B+, it cost 5597ms on the first run, but only 47ms on the second run. Is it possible cache the compile result to disk and read from the disk if the template is not changed.

tmeers commented 5 years ago

See the docs for TemplateManager and Caching.

bnuzhouwei commented 5 years ago

I read the document calfully, and searched Use external cache provider for RazorEngine #278 and Redis support #352, but still get no idea. Does any succeed in share cache in multiple applications by cache templates to disk, redis, or memcache, thanks.

paulostradioti commented 5 years ago

I'm also having this problem with the cost of the first run. All my attempts to cache the template beforehand have failed. Any insights would be much appreciated.

Thanks, everyone.

davidkeaveny commented 4 years ago

I compile the template at application startup time (in my case, a Windows service, so I add it as part of the OnStart functionality):

var templateFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Templates");
foreach (var templateFile in Directory.EnumerateFiles(templateFolder, "*.cshtml"))
{
  var template = new FileInfo(templateFile);

  try {
    Engine.Razor.Compile(template.Name);
  }
  catch (TemplateCompilationException ex) {
    Console.WriteLine($"Could not pre-compile template {template.Name}", ex);
  }
}

That compiles all the templates found in the named folder; then when it comes time to use them, I just use the .Run method:

public void RenderContent(string templateName, object model) {
  return Engine.Razor.Run(templateName, null, model);
}

As long as templateName matches the value I used for template.Name when compiling, then everything works as it should.