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...
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.
The most significant implication is Jinja being extremely slow when parsing templates with segments of whitespace in tens of thousands.
{% 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.
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).
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With