Code Irony

An Ironic Look at the State of the Art by Christopher Myers and Justin Davis

Archive for the 'python templating' Category

Fastest templating engine ever. Period.

Since web frameworks seem to be the only thing people are doing in Python these days, templating languages have become increasingly important. The problem that we at Code Irony keep running into is that they’re just not fast enough. How slow are they? We ran some profiling across one of our projects and this is what we’ve found:

graph
0.029%! Are you kidding?!? Sure, other processes take time too, but those problems look hard to solve. The obvious bottleneck that we can fix is the template rendering. The kludgy template system just has to go! We’ve decided to solve this by implementing our own template system. Since we’ve actually taken the time to think about it (unlike those other templating solutions), we’ll name it ConTemplate. It works like this: Say you want to create a basic web page, and have it show your name at the top. First create a template file that looks like this:

<h1>Hello %(name)s</h1>

After many usability tests, we found that the %(variable)s syntax is the easiest for people to understand. Furthermore, we want to be sure to separate the logic from the presentation, so we only want to replace strings. Save this file to hello.html Then, in your web framework, just import our template engine and use the code like this:
myshark

from contemplate import ConTemplate

mytemplate = ConTemplate("hello.html")

name = "Guido"

print mytemplate.render()

>  <h1>Hello Guido</h1>

Look! ConTemplate filled in your name and everything! Now, we all know that speed is the real factor in making a templating language. Check out how ConTemplate stacks up against some of the competition:

Template Processing Time
Genshi .110s
Mako .109s
ConTemplate .107s

Wow! On our first try, we beat the two fastest python templating languages! And Genshi lost by almost 3%! Imagine how fast it’ll be when version 2 comes out! You can get the benchmark test here and download the implementation here, or browse it below.


# Filename: contemplate.py
# Revision: 0.1
#
# Copyright 2008 Christopher Myers and Justin Davis
#
# “ConTemplate”
# This is by far the fastest python templating language you’ve ever used. 
#
# You have unlimited license to use this software however you want.  There
# is no warranty either expressed nor implied.  Actually, we recommend not 
# using it.  It just exists to prove a point.

import inspect

class ConTemplate(object):

    def __init__(self, filename):
        “”“Load the template”“”
        try:
            self.template = open(filename).read()
        except IOError:
            raise IOError, “No file at that location”

    def render(self, locs = None):
        “”“Render the template”“”
        if not locs:
            locs = globals()
            locs.update(inspect.currentframe(1).f_locals)
        return self.template % locs
32 comments