本文用以記錄在python開(kāi)發(fā)中遇到的性能提高技巧
持續(xù)更新中...
1.字符串
在python中string對(duì)象是不可變的,而字符串的相加會(huì)產(chǎn)生新的字符串。
當(dāng)需要迭代生成一個(gè)長(zhǎng)字符串時(shí)逐一相加不僅會(huì)影響速度也會(huì)而外增加內(nèi)存消耗(如中間結(jié)果战秋,參考java StringBuffer), 但是當(dāng)僅需鏈接很少的字符串時(shí)join方法未必明智
- join的恰當(dāng)使用
- ""%()
- format比較慢
避免
s = ""
for x in list1:
s += x
推薦
s.join(list1)
避免
s = ""
for x in list1:
s += fun(x)
推薦
list2 = [ fun(x) for x in list1 ]
s = "".join(list2)
避免
out = "<html>" + head + prologue + query + tail + "</html>"
建議
out = "<html>%(head)s%(prologue)s%(query)s%(tail)s</html>" % locals()
#變量相加過(guò)多時(shí)此方法較優(yōu)百侧,反之較差
2.循環(huán)
python解釋器在解釋for循環(huán)時(shí)會(huì)有較大的性能損耗介却,如果可以建議多使用列表解析來(lái)代替for循環(huán),另外迭代器也在優(yōu)化時(shí)間外還能夠減少內(nèi)存開(kāi)銷,在調(diào)用自寫函數(shù)時(shí)map也會(huì)提高程序性能
newlist = [s.upper() for s in oldlist]
iterator = (s.upper() for s in oldlist)
newlist = list(iterator)
在循環(huán)中盡量避免 .(點(diǎn)號(hào)操作符)的使用谴供,因?yàn)檫@往往會(huì)增加調(diào)用開(kāi)銷
避免
newlist = []
for x in oldlist:
newlist.append(x.upper())
建議
newlist = []
append = newlist.append
upper = str.upper
for x in oldlist:
append(upper(x))
3.變量
在函數(shù)中盡量使用局部變量,因?yàn)檎{(diào)用解釋器會(huì)先搜索局部變量再搜索全局變量
避免
def f1():
newlist = []
append = newlist.append
upper = str.upper
global oldlist
for x in oldlist:
append(tool1(x))
return newlist
建議
def f2(oldlist):
newlist = []
append = newlist.append
for x in oldlist:
append(tool1(x))
return newlist
4.字典
針對(duì)無(wú)初值的情況進(jìn)行優(yōu)化(提升并不多20%左右齿坷,但在一定程度上降低了可讀性)
原始方法
def f5(oldlist):
d = {}
for string in oldlist:
if string not in d:
d[string] = 0
else:
d[string] += 1
優(yōu)化方法
def f6(oldlist):
d = {}
for string in oldlist:
try:
d[string] += 1
except KeyError:
d[string] = 0
from collections import defaultdict
def f8(oldlist):
d = defaultdict(int)
for string in oldlist:
d[string] += 1