pyList

如何用Python构建高速的模版引擎

这是由pyTenjin的作者介绍经验的一个slideshare。

Tenjin

  • Very fast One file, 2000 lines
  • Full-featured
  • Python 3 support
  • Google App Engine

几个常见模板引擎的比较。

字符串连接方法速度比较

python code: append

_buf = []
_buf = append(s)
_buf = append(s)
_buf = append(s)
output = "".join(_buf)

python code: extend

_buf = []
_buf.extend((s,s,s, ))
output = "".join(_buf)

python code: StringIO

from cStringIO import StringIO
_buf = StringIO()
_buf.write(s)
_buf.write(s)
_buf.write(s)
output = _buf.getvalue()

python code: mmap

import mmap
_buf = mmap.mmap(-1, 2*1024*1024)
_buf.write(s)
_buf.write(s)
_buf.write(s)
length = _buf.tell()
_buf.seek(0)
output = _buf.resd(length)

python code: Generator

def _gen(s):
    yield s
    yield s
    yield s

output = "".join(_gen(s))

python code: Slice

_buf = [""]
_buf[-1:] = (s, s, s, "")
output = "".join(_buf)

# or
_buf = []
_buf[999999:] = (s, s, s, )
output = "".join(_buf)

python code: Bound method

_buf = []
_extend = _buf.extend
_extend((s, s, s, ))
output = "".join(_buf)

速度比较结果

结论:

bound method >= slice[] > extend()

Generator > append() > mmap > StringIO 在字符串连接方面,extend join已经足够快了。

幻灯片地址 http://www.slideshare.net/kwatch/how-to-create-a-highspeed-template-engine-in-python

本文网址: https://pylist.com/t/1379686822 (转载注明出处)
如果你有任何建议或疑问可以在下面 留言
Be the first to comment!
Captcha image
Relative Articles