Python - append VS extend efficiency

前端 未结 3 688
余生分开走
余生分开走 2020-12-28 09:13

Here is some code that I wrote using Python:

from math import sqrt
abundant_list = []

for i in range(12,28123+1):
    dividor_list = [1]
    for j in range(         


        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-28 09:26

    import timeit
    
    def append2x(foo):
        foo.append(1)
        foo.append(1)
    
    def extend_lst(foo):
        foo.extend([1,1])
    
    def extend_tup(foo):
        foo.extend((1,1))
    
    
    l1 = []
    l2 = []
    l3 = []
    
    print timeit.timeit('append2x(l1)',setup = 'from __main__ import append2x,l1')
    print timeit.timeit('extend_lst(l2)',setup = 'from __main__ import extend_lst,l2')
    print timeit.timeit('extend_tup(l3)',setup = 'from __main__ import extend_tup,l3')
    

    Here's a simple benchmark. My results (os-X, 10.5.8, core2duo, FWIW):

    0.520906925201  #append
    0.602569103241  #extend-list
    0.357008934021  #extend-tuple
    

    And the same ordering of the results my linux box (Ubuntu, x86-64 core i7):

    0.307395935059  #append
    0.319436073303  #extend-list
    0.238317012787  #extend-tuple
    

    To me, this says that extend is quicker than append, but that creating a list is relatively expensive compared to creating a tuple


    EDIT

    Pointed out in the comments below, because of the immutability of tuples, the interpreter can optimize the creation of the tuple out (it creates the tuple once and re-uses it over and over). If we change the code to:

    def extend_lst(foo):  
        v = 1
        foo.extend([v,v]) 
    
    def extend_tup(foo):
        v = 1
        foo.extend((v,v))
    

    The timings are virtually identical:

    0.297003984451  #append
    0.344678163528  #extend-list
    0.292304992676  #extend-tuple
    

    Although tuple still consistently beats the list version and barely edges out the append version for all of the trials I have done.

    One thing that I'm taking away from this is that if you're iterating over an object that consists of all literals, choose a tuple over a list. If it doesn't consist entirely of literals, then it really doesn't matter whether you choose list or tuple.

提交回复
热议问题