Skip to content
Myr

some performance improvements

Before adoption: this commit came in with the history the project adopted, so no landing records it.

--HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent 0611e49 · Browse files · 5 files+100 added−24 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+100 added−24 removed

  • other:+100 added−24 removed

5 files+100 added−24 removed

modified:examples/bench.py+81 added-9 removed
1import sys2from django.conf import settings3settings.configure()4from django.template import Template as DjangoTemplate, Context as DjangoContext5from jinja2 import Environment as JinjaEnvironment6from mako.template import Template as MakoTemplate7from genshi.template import MarkupTemplate as GenshiTemplate8from Cheetah.Template import Template as CheetahTemplate9from timeit import Timer1011context = {12 'page_title': 'mitsuhiko\'s benchmark',13 'table': [dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10) for x in range(1000)]14}1516jinja_template = JinjaEnvironment(17 line_statement_prefix='%',18 variable_start_string="${",
1 unmodified line
20).from_string("""\21<!doctype html>22<html>23 <head>17 <title>${page_title|e}24 <title>${page_title|e}</title>25 </head>26 <body>27 <div class="header">28 <h1>${page_title|e}</h1>
25 unmodified lines
54django_template = DjangoTemplate("""\55<!doctype html>56<html>57 <head>51 <title>{{ page_title }}58 <title>{{ page_title }}</title>59 </head>60 <body>61 <div class="header">62 <h1>{{ page_title }}</h1>
21 unmodified lines
84mako_template = MakoTemplate("""\85<!doctype html>86<html>87 <head>81 <title>${page_title|h}88 <title>${page_title|h}</title>89 </head>90 <body>91 <div class="header">92 <h1>${page_title|h}</h1>
17 unmodified lines
110 </body>111</html>\112""")113107context = {108 'page_title': 'mitsuhiko\'s benchmark',109 'table': [dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10) for x in range(1000)]110}114genshi_template = GenshiTemplate("""\115<html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/">116 <head>117 <title>${page_title}</title>118 </head>119 <body>120 <div class="header">121 <h1>${page_title}</h1>122 </div>123 <ul class="navigation">124 <li py:for="href, caption in [125 ('index.html', 'Index'),126 ('downloads.html', 'Downloads'),127 ('products.html', 'Products')]"><a href="${href}">${caption}</a></li>128 </ul>129 <div class="table">130 <table>131 <tr py:for="row in table">132 <td py:for="cell in row">${cell}</td>133 </tr>134 </table>135 </div>136 </body>137</html>\138""")139140cheetah_template = CheetahTemplate("""\141#import cgi142<!doctype html>143<html>144 <head>145 <title>$cgi.escape($page_title)</title>146 </head>147 <body>148 <div class="header">149 <h1>$cgi.escape($page_title)</h1>150 </div>151 <ul class="navigation">152 #for $href, $caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')]:153 <li><a href="$cgi.escape($href)">$cgi.escape($caption)</a></li>154 #end for155 </ul>156 <div class="table">157 <table>158 #for $row in $table:159 <tr>160 #for $cell in $row:161 <td>$cell</td>162 #end for163 </tr>164 #end for165 </table>166 </div>167 </body>168</html>\169""", searchList=[dict(context)])170171def test_jinja():172 jinja_template.render(context)173174def test_django():
3 unmodified lines
178179def test_mako():180 mako_template.render(**context)181182def test_genshi():183 genshi_template.generate(**context).render('html', strip_whitespace=False)184185def test_cheetah():186 unicode(cheetah_template)187188sys.stdout.write('\r%s\n%s\n%s\n' % (189 '=' * 80,190 'Template Engine BigTable Benchmark'.center(80),191 '-' * 80192))124for test in 'jinja', 'mako', 'django':193for test in 'jinja', 'mako', 'django', 'genshi', 'cheetah':194 t = Timer(setup='from __main__ import test_%s as bench' % test,195 stmt='bench()')127 print '%-20s%.4fms' % (test, t.timeit(number=20) / 20)196 sys.stdout.write('> %-20s<running>' % test)197 sys.stdout.flush()198 sys.stdout.write('\r %-20s%.4f ms\n' % (test, t.timeit(number=100) / 100))199sys.stdout.write('=' * 80 + '\n')
modified:jinja2/compiler.py+7 added-7 removed
12 unmodified lines
13from cStringIO import StringIO14from jinja2 import nodes15from jinja2.visitor import NodeVisitor, NodeTransformer16from jinja2.exceptions import TemplateAssertionError17from jinja2.runtime import StaticLoopContext17from jinja2.runtime import StaticLoopContext, concat18from jinja2.utils import Markup192021operators = {
705 unmodified lines
727 self.indent()728 self.pull_locals(macro_frame, indent=False)729 self.writeline('%s = []' % buf)730 self.blockvisit(node.body, macro_frame, indent=False)731 self.writeline("return Markup(u''.join(%s))" % buf)731 self.writeline("return Markup(concat(%s))" % buf)732 self.outdent()733 self.newline()734 if frame.toplevel:735 self.write('context[%r] = ' % node.name)
19 unmodified lines
755 self.indent()756 self.pull_locals(call_frame, indent=False)757 self.writeline('%s = []' % buf)758 self.blockvisit(node.body, call_frame, indent=False)759 self.writeline("return Markup(u''.join(%s))" % buf)759 self.writeline("return Markup(concat(%s))" % buf)760 self.outdent()761 arg_tuple = ', '.join(repr(x.name) for x in node.args)762 if len(node.args) == 1:763 arg_tuple += ','
29 unmodified lines
793 if frame.buffer is None:794 self.writeline('yield ', node)795 else:796 self.writeline('%s.append(' % frame.buffer, node)797 self.visit_Filter(node.filter, filter_frame, "u''.join(%s)" % buf)797 self.visit_Filter(node.filter, filter_frame, 'concat(%s)' % buf)798 if frame.buffer is not None:799 self.write(')')800801 def visit_ExprStmt(self, node, frame):
39 unmodified lines
841 # if we have less than 3 nodes we just yield them842 if len(body) < 3:843 for item in body:844 if isinstance(item, list):845 val = repr(u''.join(item))845 val = repr(concat(item))846 if frame.buffer is None:847 self.writeline('yield ' + val)848 else:849 self.writeline('%s.append(%s)' % (frame.buffer, val))
12 unmodified lines
862 format = []863 arguments = []864 for item in body:865 if isinstance(item, list):866 format.append(u''.join(item).replace('%', '%%'))866 format.append(concat(item).replace('%', '%%'))867 else:868 format.append('%s')869 arguments.append(item)870 if frame.buffer is None:871 self.writeline('yield ')872 else:873 self.writeline('%s.append(' % frame.buffer)874 self.write(repr(u''.join(format)) + ' % (')874 self.write(repr(concat(format)) + ' % (')875 idx = -1876 self.indent()877 for argument in arguments:878 self.newline(argument)
207 unmodified lines
modified:jinja2/environment.py+4 added-4 removed
11 unmodified lines
12from jinja2.lexer import Lexer13from jinja2.parser import Parser14from jinja2.optimizer import optimize15from jinja2.compiler import generate16from jinja2.runtime import Undefined, TemplateContext16from jinja2.runtime import Undefined, TemplateContext, concat17from jinja2.debug import translate_exception18from jinja2.utils import import_string, LRUCache, Markup19from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE20
279 unmodified lines
300301 def render(self, *args, **kwargs):302 """Render the template into a string."""303 try:304 return u''.join(self.generate(*args, **kwargs))304 return concat(self.generate(*args, **kwargs))305 except:306 # hide the `generate` frame307 exc_type, exc_value, tb = sys.exc_info()308 raise exc_type, exc_value, tb.tb_next
85 unmodified lines
394class IncludedTemplate(object):395 """Represents an included template."""396397 def __init__(self, template, context):398 body = Markup(u''.join(template.root_render_func(context)))398 body = Markup(concat(template.root_render_func(context)))399 self.__dict__.update(context.get_exported())400 self._name = template.name401 self._rendered_body = body402
44 unmodified lines
447 c_size += 1448 except StopIteration:449 if not c_size:450 raise451 yield u''.join(buf)451 yield concat(buf)452 del buf[:]453 c_size = 0454455 self.buffered = True
12 unmodified lines
modified:jinja2/optimizer.py+2 added-2 removed
16 unmodified lines
17 :license: GNU GPL.18"""19from jinja2 import nodes20from jinja2.visitor import NodeVisitor, NodeTransformer21from jinja2.runtime import LoopContext21from jinja2.runtime import LoopContext, concat222324def optimize(node, environment, context_hint=None):25 """The context hint can be used to perform an static optimization
84 unmodified lines
110 buffer.append(item)111112 # now check if we can evaluate the filter at compile time.113 try:114 data = node.filter.as_const(u''.join(buffer))114 data = node.filter.as_const(concat(buffer))115 except nodes.Impossible:116 return node117118 context.pop()
83 unmodified lines
modified:jinja2/runtime.py+6 added-2 removed
12 unmodified lines
13from jinja2.exceptions import UndefinedError141516__all__ = ['LoopContext', 'StaticLoopContext', 'TemplateContext',17 'Macro', 'Markup', 'missing']17 'Macro', 'Markup', 'missing', 'concat']181920# special singleton representing missing values for the runtime21missing = object()222324# concatenate a list of strings and convert them to unicode.25concat = u''.join262728class TemplateContext(object):29 """Holds the variables of the local template or of the global one. It's30 not save to use this class outside of the compiled code. For example31 update and other methods will not work as they seem (they don't update
87 unmodified lines
119 self._context = context120 self._render_func = render_func121122 def __call__(self):119 return Markup(u''.join(self._render_func(self._context)))123 return Markup(concat(self._render_func(self._context)))124125 def __repr__(self):126 return '<%s %r>' % (127 self.__class__.__name__,
222 unmodified lines