Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Speed comparison: server-generated HTML vs templates?

I'm using Google App Engine's version of Django templates in Python.

Is there a major performance difference between putting loops in the template vs putting it in the python page handlers?

For example, I'm comparing something like this:

{% for i in items %}
   <div id="item_{{i.key}}">    
       {{i.text}}
   </div>
{% endfor %}

Vs something like this inside my python code:

def returnHtml(items):
  item_array = []
  for i in items:
     item_array.append("<div id='item_%s'>%s</div>" % (i.id, i.text)
  return "".join(item_array)

... which then gets directly inserted into a django template in a tag like:

{{ item_html }}

This is a trivial example, realistically, I've got more complex loops inside of loops, etc. I like putting the logic inside of the python code because it's much easier to maintain. But I'm worried about the impact on performance.

Any thoughts? Thanks.

like image 315
Cuga Avatar asked Feb 25 '23 04:02

Cuga


1 Answers

The loss in readability and maintainability of your code probably outweigh any performance gains you'll get. You can find many benchmarks of Python template engines. All of the popular template engines perform acceptably.

If you do not like the shortcomings in django templates, use something better. I personally use (and highly recommend) Mako and I know several others who like Jinja2.

like image 57
Robert Kluin Avatar answered Mar 16 '23 14:03

Robert Kluin