2015-04-12 29 views
0

我有一個項目的字典。我想處理除了以「_」開頭的鍵以外的所有項目。使用繼續和不使用循環在Python中是否有性能差異?

是否有這樣做的性能差異:

if items.startswith("_"): 
    continue 

<code that should be done for items that keys do not start with "_"> 

if not items.startswith("_"): 
    <do code that should be done for items that keys do not start with "_"> 
+0

是的,第二將是最好的。 –

+3

可能沒有有意義的性能差異。選擇一個最具可讀性的人(如果這是一個問題,首選方法是防止箭頭代碼)。 – Brian

+5

做什麼最好,除非你已經顯示它是一個瓶頸。 –

回答

1

我想出了一個簡單的測試程序進行這個使用timeit模塊爲每wwii意見。這是一個無用的腳本;它所做的就是將每個感興趣的關鍵字(即不以'_'開頭的關鍵字)存儲在每次被覆蓋的變量中。

import timeit 

trials = 1000000 

setup = """ 
foo = {'key0': 'val0', '_key1': 'val1', '_key2': 'val2', 'key3': 'val3', 'key4': 'val4'} 
""" 

run = """ 
for key in foo: 
    if key.startswith('_'): 
     continue 
    bar = key 
""" 
t = timeit.Timer(run, setup) 
print 'Using ''continue'': %f' % min(t.repeat(3, trials)) 

run = """ 
for key in foo: 
    if not key.startswith('_'): 
     bar = key 
""" 
t = timeit.Timer(run, setup) 
print 'Using ''if not'': %f' % min(t.repeat(3, trials)) 

這會執行三次運行每個塊1,000,000次的測試並返回最小執行時間。下面是結果:

Using continue: 1.880194
Using if not: 1.767904

這些結果運行之間略有不同,但趨勢始終是相同的:第二個結構成爲比第1 1,000,000奔跑少大約100毫秒。這意味着每次運行的差異大約爲100 ns。我懷疑有人會注意到這一點。

在這一點上它確實是一個可讀性的問題。對於這樣一小塊代碼,這可能無論如何都不重要。任何知道一個小Python的人都應該能夠說出這兩者的含義。就個人而言,我會選擇第二種選擇,但我也沒有看到任何問題。