简体   繁体   中英

Is there a performance difference of breaking out using continue and using not in a loop in Python?

I have a dictionary of items. I want to process all items except the ones which keys start with "_".

Is there a performance difference of doing:

if items.startswith("_"):
   continue

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

vs.

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

I came up with a simple test program for this using the timeit module as per the advice of wwii . It's a useless script; all it does is store each key of interest (ie the ones that don't start with '_' ) in a variable, which is overwritten each time.

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))

This does three tests of running each block 1,000,000 times and returns the minimum execution time. Here are the results:

Using continue: 1.880194
Using if not: 1.767904

These results vary slightly between runs, but the trend is always the same: The second structure takes around 100 ms less than the first for 1,000,000 runs. That means the difference is on the order of 100 ns for each run. I doubt anyone would notice that.

At this point it's really a question of readability. For such a small block of code, it probably doesn't matter either way. Anyone who knows a little Python should be able to tell what both of those mean. Personally, I would choose the second option, but I don't see a problem with either.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM