深入理解Python 代码优化详解(3)
from time import time
t = time()
s = ""
list = ['a','b','b','d','e','f','g','h','i','j','k','l','m','n']
for i in range (10000):
for substr in list:
s+= substr
print "total run time:"
print time()-t
同时要避免:
s = ""
for x in list:
s += func(x)
而是要使用:
slist = [func(elt) for elt in somelist]
s = "".join(slist)
2.当对字符串可以使用正则表达式或者内置函数来处理的时候,选择内置函数。如 str.isalpha(),str.isdigit(),str.startswith((‘x', ‘yz')),str.endswith((‘x', ‘yz'))
3.对字符进行格式化比直接串联读取要快,因此要使用
out = "<html>%s%s%s%s</html>" % (head, prologue, query, tail)
而避免
out = "<html>" + head + prologue + query + tail + "</html>"
使用列表解析(list comprehension)和生成器表达式(generator expression)
列表解析要比在循环中重新构建一个新的 list 更为高效,因此我们可以利用这一特性来提高运行的效率。
from time import time
t = time()
list = ['a','b','is','python','jason','hello','hill','with','phone','test',
'dfdf','apple','pddf','ind','basic','none','baecr','var','bana','dd','wrd']
total=[]
for i in range (1000000):
for w in list:
total.append(w)
print "total run time:"
print time()-t
使用列表解析:
for i in range (1000000):
a = [w for w in list]
上述代码直接运行大概需要 17s,而改为使用列表解析后 ,运行时间缩短为 9.29s。将近提高了一半。生成器表达式则是在 2.4 中引入的新内容,语法和列表解析类似,但是在大数据量处理时,生成器表达式的优势较为明显,它并不创建一个列表,只是返回一个生成器,因此效率较高。在上述例子上中代码 a = [w for w in list] 修改为 a = (w for w in list),运行时间进一步减少,缩短约为 2.98s。
其他优化技巧
1、如果需要交换两个变量的值使用 a,b=b,a 而不是借助中间变量 t=a;a=b;b=t;