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

这是由pyTenjin的作者介绍经验的一个slideshare,介绍如何用Python构建高速的模版引擎。其经验和方法很值得我们学习。

关于 Tenjin 模版

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

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

模板引擎比较

字符串连接方法速度比较

python 代码: append

1
2
3
4
5
_buf = []
_buf = append(s)
_buf = append(s)
_buf = append(s)
output = "".join(_buf)

python 代码: extend

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

python 代码: StringIO

1
2
3
4
5
6
from cStringIO import StringIO
_buf = StringIO()
_buf.write(s)
_buf.write(s)
_buf.write(s)
output = _buf.getvalue()

python 代码: mmap

1
2
3
4
5
6
7
8
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 代码: Generator

1
2
3
4
5
6
def _gen(s):
    yield s
    yield s
    yield s

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

python 代码: Slice

1
2
3
4
5
6
7
8
_buf = [""]
_buf[-1:] = (s, s, s, "")
output = "".join(_buf)

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

python 代码: Bound method

1
2
3
4
_buf = []
_extend = _buf.extend
_extend((s, s, s, ))
output = "".join(_buf)

速度比较结果

/static/upload/1379685783.jpg

结论

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/topic/30.html 转摘请注明来源

Suggested Topics

3行 Python 代码解简单的一元一次方程

一元一次方程:只含有一个未知数(即“元”),并且未知数的最高次数为1(即“次”)的整式方程叫做一元一次方程(英文名:`linear equation with one unknown`)。...

用Tornado 构建一个 Comet 应用

Comet -- 基于 HTTP 长连接、无须在浏览器端安装插件的“服务器推”技术为“Comet”,这里介绍用Tornado 构建一个 Comet 应用的经验。...

python 高效的list 去重方式

list 去重是编程中经常用到的,python 的去重方式很灵活,下面介绍多种去重方式,并比较得出最高效的方式。...

Leave a Comment