paint-brush
How you can dramatically speed up your Django site with Django’s cached template loaderby@andrewwidjaja
10,528 reads
10,528 reads

How you can dramatically speed up your Django site with Django’s cached template loader

by Andrew WidjajaApril 27th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

I was profiling a Django 1.8 site when I noticed something peculiar.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - How you can dramatically speed up your Django site with Django’s cached template loader
Andrew Widjaja HackerNoon profile picture

I was profiling a Django 1.8 site when I noticed something peculiar.

The function django.template.engine.get_template was called 50 times and took a cumulative time of 229 ms, almost half the page load time.

The site uses a lot of template tags to render different elements on the page, such as ad positions and related story boxes.

Django’s template system will read and compile a template every time it is rendered. This happens quickly, but when you render multiple templates on each page it can add up, just like in my case.

After searching around for a solution I discovered django.template.loaders.cached.Loader, which when enabled stores compiled templates in memory, reducing the time to retrieve templates.

Once cached template loader was enabled on the site the cumulative time of django.template.engine.get_template went right down to 1 ms, reducing page load times by ~200 ms.

Cached template loader was introduced in Django 1.2, but wasn’t enabled by default and it can be quite easy to miss.

Before you enable cached template loader you will need to ensure that all your custom template tags are thread-safe.

Starting from Django 1.11 cached template loader is enabled by default when the setting DEBUG is set as False.

If you are still on an older version of Django and use a lot of template tags, enable cached template loader, it can speed up your site tremendously.

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.

To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!