Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RazorEngine Memory Usage

Tags:

razorengine

I have created a windows service to build and send emails. I am using the Razor Engine to parse the email templates. I am using a dynamic ExpandoObject to create the model.

My problem is when each email is created and sent the memory is increasing but it is never been released. I have profiled the service with Ants Memory profiler(I haven't used this before) but it is showing the following results:

With Razor Engine

Parsing 200 emails with Razor.Parse(text,model)

Generation 1: 12.9kb

Generation 2: 15.88mb

Large Object Heap: 290.9kb

Unused memory allocated to .NET: 3.375mb

Unmanaged: 69.51mb

Total number of memory fragments: 197

No Razor Engine

Returning 200 emails unparsed text.

Generation 1: 13.87kb

Generation 2: 3.798mb

Large Object Heap: 95.58kb

Unused memory allocated to .NET: 4.583mb

Unmanaged: 44.58mb

Total number of memory fragments: 7

With Razor the biggest generation 2 instances are:

System.Reflection.Emit __FixUpData[] - 2,447,640 live bytes, 3,138 instances

Has anyone any idea why the objects aren't being released and the Generation 2 is growing? Is there a way to have a new instance of the RazorEngine each time I want to parse a template and when its finished it will not be referenced and will go to the GC.

Ive tried creating a new instance of Template service each time I parse a template but this hasnt made a difference

using (ITemplateService templateService = new TemplateService())
{
     result = templateService.Parse<ExpandoObject>(text, model);
}
like image 393
ministrymason Avatar asked Sep 06 '12 13:09

ministrymason


2 Answers

Each time you parse a template, RazorEngine compiles an in-memory assembly.
That can get expensive.

You should re-use your templates as much as possible.

like image 145
SLaks Avatar answered Sep 19 '22 19:09

SLaks


Old question, but to activate the template cache you must supply the "cache" argument to the Parse method (which can/should be the path to your template) :

return RazorViewService.Parse(File.ReadAllText(path), model, null, cache);
like image 44
Profet Avatar answered Sep 23 '22 19:09

Profet