Developer forum

Forum » Templates » Enhancing performance in cshtml

Enhancing performance in cshtml

Søren Heide Larsen
Søren Heide Larsen
Reply

Hi all,

As I was building a new site for one of our customers in Dynamicweb9 I experienced that the page was quite slow at loading the first time. I narrowed it down to the compilation of the cshtml file, so the performance was as expected when reloading. It generally takes 2-3 seconds to build the cshtml file (at last in my solution), so when dealing with a page with several modules this quickly adds up. You may state that this is not an issue as the following hit will use the cached compilation, but when dealing with a test site or a less frequent visited pages with custom layout, this may actually result in a bad customer experience.

This made me wonder how to fix this, so I fired up my Visual Studio and wrote a little handler that I now want to share with you all. You may trigger this through a scheduled task, which simply compiles all cshtml templates and takes away the entire performance hit for the compiling process, thus making the page feel a lot faster. Enjoy!

public class CshtmlWarmup : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        // Write as stream, so we can follow what is going on
        context.Response.Buffer = false;
        context.Response.ContentType = "text/event-stream";
        using (var writer = new StreamWriter(context.Response.OutputStream))
        {

            // Find all *.cshtml files in Templates folder
            var templatesFolder = HostingEnvironment.MapPath("/Files/Templates");
            var files = new DirectoryInfo(templatesFolder).GetFiles("*.cshtml", SearchOption.AllDirectories);
            writer.WriteLine($"Found {files.Length} cshtml files, starting to warmup");
            writer.Flush();

            foreach (var file in files)
            {
                // Get the Dynamicweb way of writing a template path
                var filePath = file.FullName.Substring(templatesFolder.Length);
                writer.Write("\t" + filePath);
                writer.Flush();
                var from = DateTime.Now;
                try
                {
                    // New Template actually does the compiling
                    new Dynamicweb.Rendering.Template(filePath);

                    // Report how long time it took
                    writer.Write($" - compiled in {(DateTime.Now - from).TotalMilliseconds:N2} ms");
                }
                catch (Exception e)
                {
                    // Report how long time it took
                    writer.Write($" - FAILED in {(DateTime.Now - from).TotalMilliseconds:N2} ms");
                }
                writer.Write("\r\n");
                writer.Flush();
            }
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

 


Replies

 

You must be logged in to post in the forum