用着Python学量化我的Python自学之路程序员

Python代码性能的基础优化技巧

2016-12-19  本文已影响350人  陈码工

String Concatenation

#bad
s = "" 
for substring in list:    
        s += substring

#good
"".join(list)
#bad with direct concatenation
out = "<html>" + head + prologue + query + tail + "</html>"
#good with format output
out = "<html>%s%s%s%s</html>" % (head, prologue, query, tail)

Loops

#bad
newlist = [] 
for word in oldlist:    
        newlist.append(word.upper())
#good
newlist = map(str.upper, oldlist)
#good: list comprehension
newlist = [s.upper() for s in oldlist]
#good: generator expression
iterator = (s.upper() for s in oldlist)

Avoiding dots

#bad: 
newlist = [] 
for word in oldlist:    
        newlist.append(word.upper())

#good: store the refered functions
upper = str.upper  #store the str.upper function
newlist = [] 
append = newlist.append  #store the newlist.append function
for word in oldlist:    
        append(upper(word))

Local Variable(Function rocks)

def func(): 
upper = str.upper 
newlist = [] 
append = newlist.append 
for word in oldlist: 
    append(upper(word)) 
return newlist

Time consumption of abovementioned methods:

Version Time (seconds)
Basic loop 3.47
Eliminate dots 2.45
Local variable & no dots 1.79
Using map function 0.54

Dict

#ordinary
wdict = {}
for word in words: 
    if word not in wdict: 
        wdict[word] = 0 
        wdict[word] += 1
#good
wdict = {}
get = wdict.get
for word in words: 
    wdict[word] = get(word, 0) + 1 
#多使用大名鼎鼎的dict.get(key, defaultValue)方法
上一篇 下一篇

猜你喜欢

热点阅读