Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - rendering many templates using templatetags is very slow

Say, I have a page with a photo gallery. Each thumbnail has e.g. a photo, country, author and so on. I render these items/widgets using template tags (which load specified templates) - it goes that way because of DRY (I use these items/widgets separately in different places on the page).

And it is very slow.

I have performed some profiling using django-debug-toolbar:

SQL Queries: default 84.81 ms (147 queries)

But:

Total CPU time: 5768.360 msec

Which is too long to wait.

After some analysis it turned out that the main culprit is templating enginge.

When I want to display e.g. 150 photos, 600 associated items/widgets are being rendered via templates. It means 600 I/O operations or even more. Moving these widgets to main template solves the problem, but does not keep DRY.

So my question is how one can avoid such a behaviour? Be DRY and slow or no-DRY and fast? I'd rather be DRY and fast...

like image 930
laszchamachla Avatar asked Feb 07 '12 19:02

laszchamachla


People also ask

Is Django template slow?

Django templates are slow compared to Jinja2 templates. This may be to do with Jinja2 compiling the templates or perhaps due to the excessive number of function calls Django makes while rendering templates. However, in my experience Django templates are fast enough.

Is Jinja slow?

The most significant implication is Jinja being extremely slow when parsing templates with segments of whitespace in tens of thousands.

What does {% %} do in Django?

{% extends variable %} uses the value of variable . If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.

How many arguments does the tag method uses for registering custom tags?

Registering the tag The tag() method takes two arguments: The name of the template tag – a string. If this is left out, the name of the compilation function will be used. The compilation function – a Python function (not the name of the function as a string).


1 Answers

After several hours of profiling and searching...

Thanks for your help, but in this case it seems to me that the best solution so far is to use Template fragment caching:

I tried it and gained 70-80% speed performance!

{% load cache %}
{% cache 3600 mywidget_id %}
    .. rendered mywidget is cached ..
{% endcache %}
like image 72
laszchamachla Avatar answered Sep 22 '22 20:09

laszchamachla