perfomance of len(List) vs reading a variable

前端 未结 4 556
名媛妹妹
名媛妹妹 2021-01-12 17:17

A similar question has already been ask Cost of len() function here. However, this question looks at the cost of len it self. Suppose, I have a code that repea

4条回答
  •  北荒
    北荒 (楼主)
    2021-01-12 17:40

    Using l = len(li) is faster:

    python -m timeit -s "li = [1, 2, 3]" "len(li)"
    1000000 loops, best of 3: 0.239 usec per loop
    
    python -m timeit -s "li = [1, 2, 3]; l = len(li)" "l"
    10000000 loops, best of 3: 0.0949 usec per loop
    

提交回复
热议问题