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
Provenance
- Commit
de6bf71- Tree
3ce3005- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
0611e49
5 files changed+100 added−24 removed
modified:examples/bench.py+81 added-9 removed
1+import sys2 from django.conf import settings3 settings.configure()4 from django.template import Template as DjangoTemplate, Context as DjangoContext5 from jinja2 import Environment as JinjaEnvironment6 from mako.template import Template as MakoTemplate7+from genshi.template import MarkupTemplate as GenshiTemplate8+from Cheetah.Template import Template as CheetahTemplate9 from timeit import Timer10 11+context = {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+}15 16 jinja_template = JinjaEnvironment(17 line_statement_prefix='%',18 variable_start_string="${",1 unmodified line20 ).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 lines54 django_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 lines84 mako_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 lines110 </body>111 </html>\112 """)113 107-context = {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-}114+genshi_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+""")139 140+cheetah_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)])170+171 def test_jinja():172 jinja_template.render(context)173 174 def test_django():3 unmodified lines178 179 def test_mako():180 mako_template.render(**context)181 182+def test_genshi():183+ genshi_template.generate(**context).render('html', strip_whitespace=False)184 185+def test_cheetah():186+ unicode(cheetah_template)187+188+sys.stdout.write('\r%s\n%s\n%s\n' % (189+ '=' * 80,190+ 'Template Engine BigTable Benchmark'.center(80),191+ '-' * 80192+))124-for test in 'jinja', 'mako', 'django':193+for 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))199+sys.stdout.write('=' * 80 + '\n')modified:jinja2/compiler.py+7 added-7 removed
12 unmodified lines13 from cStringIO import StringIO14 from jinja2 import nodes15 from jinja2.visitor import NodeVisitor, NodeTransformer16 from jinja2.exceptions import TemplateAssertionError17-from jinja2.runtime import StaticLoopContext17+from jinja2.runtime import StaticLoopContext, concat18 from jinja2.utils import Markup19 20 21 operators = {705 unmodified lines727 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 lines755 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 lines793 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(')')800 801 def visit_ExprStmt(self, node, frame):39 unmodified lines841 # 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 lines862 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 linesmodified:jinja2/environment.py+4 added-4 removed
11 unmodified lines12 from jinja2.lexer import Lexer13 from jinja2.parser import Parser14 from jinja2.optimizer import optimize15 from jinja2.compiler import generate16-from jinja2.runtime import Undefined, TemplateContext16+from jinja2.runtime import Undefined, TemplateContext, concat17 from jinja2.debug import translate_exception18 from jinja2.utils import import_string, LRUCache, Markup19 from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE20 279 unmodified lines300 301 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_next85 unmodified lines394 class IncludedTemplate(object):395 """Represents an included template."""396 397 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 lines447 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 = 0454 455 self.buffered = True12 unmodified linesmodified:jinja2/optimizer.py+2 added-2 removed
16 unmodified lines17 :license: GNU GPL.18 """19 from jinja2 import nodes20 from jinja2.visitor import NodeVisitor, NodeTransformer21-from jinja2.runtime import LoopContext21+from jinja2.runtime import LoopContext, concat22 23 24 def optimize(node, environment, context_hint=None):25 """The context hint can be used to perform an static optimization84 unmodified lines110 buffer.append(item)111 112 # 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 node117 118 context.pop()83 unmodified linesmodified:jinja2/runtime.py+6 added-2 removed
12 unmodified lines13 from jinja2.exceptions import UndefinedError14 15 16 __all__ = ['LoopContext', 'StaticLoopContext', 'TemplateContext',17- 'Macro', 'Markup', 'missing']17+ 'Macro', 'Markup', 'missing', 'concat']18 19 20 # special singleton representing missing values for the runtime21 missing = object()22 23 24+# concatenate a list of strings and convert them to unicode.25+concat = u''.join26+27+28 class 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 update87 unmodified lines119 self._context = context120 self._render_func = render_func121 122 def __call__(self):119- return Markup(u''.join(self._render_func(self._context)))123+ return Markup(concat(self._render_func(self._context)))124 125 def __repr__(self):126 return '<%s %r>' % (127 self.__class__.__name__,222 unmodified lines