Only index needed: enumerate or (x)range?

后端 未结 8 2143
长发绾君心
长发绾君心 2020-11-29 09:46

If I want to use only the index within a loop, should I better use the range/xrange function in combination with len()

a = [1,2,3]         


        
8条回答
  •  清酒与你
    2020-11-29 10:34

    I ran a time test and found out range is about 2x faster than enumerate. (on python 3.6 for Win32)

    best of 3, for len(a) = 1M

    • enumerate(a): 0.125s
    • range(len(a)): 0.058s

    Hope it helps.

    FYI: I initialy started this test to compare python vs vba's speed...and found out vba is actually 7x faster than range method...is it because of my poor python skills?

    surely python can do better than vba somehow

    script for enumerate

    import time
    a = [0]
    a = a * 1000000
    time.perf_counter()
    
    for i,j in enumerate(a):
        pass
    
    print(time.perf_counter())
    

    script for range

    import time
    a = [0]
    a = a * 1000000
    time.perf_counter()
    
    for i in range(len(a)):
        pass
    
    print(time.perf_counter())
    

    script for vba (0.008s)

    Sub timetest_for()
    Dim a(1000000) As Byte
    Dim i As Long
    tproc = Timer
    For i = 1 To UBound(a)
    Next i
    Debug.Print Timer - tproc
    End Sub
    

提交回复
热议问题