如何用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

python 高效的list 去重方式

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

Python List 按键高效排序方法

Python含有许多古老的排序规则,这些规则在你创建定制的排序方法时会占用很多时间,而这些排序方法运行时也会拖延程序实际的运行速度。...

python 半角全角的相互转换

全角与半角在中文输入法里经常要接触到,后台在处理用户输入数据时需要对半角全角的相互转换。下面是python 实现的半角全角的相互转换功能。...

Leave a Comment