如何用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://py.youbbs.org/topic/30.html 转摘请注明来源

Suggested Topics

python 解析电子书的信息

epub 书是可供人们下载的开放性资源格式的电子图书。epub 文件通常与类似亚马逊Kindle 这样的电子阅读器不兼容。...

Python List 按键高效排序方法

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

给ssdb python 接口提速

SSDB 是个新兴的数据库,其数据库的特点简单,性能高效,有好多python 接口,个人比较后选择一个最理想的,但还有提速空间,这里仅作经验分享。...

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

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

python编程中常用的12种基础知识总结

python编程中常用的12种基础知识总结:正则表达式替换,遍历目录方法,列表按列排序、去重,字典排序,字典、列表、字符串互转,时间对象操作,命令行参数解析(getopt),print 格式化输出,进制转换,Python调用系统命令或者脚本,Python 读写文件。...

用Tornado 构建一个 Comet 应用

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

Leave a Comment