List comprehension vs. lambda + filter

前端 未结 14 2374
挽巷
挽巷 2020-11-22 02:01

I happened to find myself having a basic filtering need: I have a list and I have to filter it by an attribute of the items.

My code looked like this:



        
14条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 02:55

    Curiously on Python 3, I see filter performing faster than list comprehensions.

    I always thought that the list comprehensions would be more performant. Something like: [name for name in brand_names_db if name is not None] The bytecode generated is a bit better.

    >>> def f1(seq):
    ...     return list(filter(None, seq))
    >>> def f2(seq):
    ...     return [i for i in seq if i is not None]
    >>> disassemble(f1.__code__)
    2         0 LOAD_GLOBAL              0 (list)
              2 LOAD_GLOBAL              1 (filter)
              4 LOAD_CONST               0 (None)
              6 LOAD_FAST                0 (seq)
              8 CALL_FUNCTION            2
             10 CALL_FUNCTION            1
             12 RETURN_VALUE
    >>> disassemble(f2.__code__)
    2           0 LOAD_CONST               1 ( at 0x10cfcaa50, file "", line 2>)
              2 LOAD_CONST               2 ('f2..')
              4 MAKE_FUNCTION            0
              6 LOAD_FAST                0 (seq)
              8 GET_ITER
             10 CALL_FUNCTION            1
             12 RETURN_VALUE
    

    But they are actually slower:

       >>> timeit(stmt="f1(range(1000))", setup="from __main__ import f1,f2")
       21.177661532000116
       >>> timeit(stmt="f2(range(1000))", setup="from __main__ import f1,f2")
       42.233950221000214
    

提交回复
热议问题