Are list-comprehensions and functional functions faster than “for loops”?

后端 未结 7 1623
梦如初夏
梦如初夏 2020-11-22 01:48

In terms of performance in Python, is a list-comprehension, or functions like map(), filter() and reduce() faster than a for loop? Why

7条回答
  •  情书的邮戳
    2020-11-22 02:02

    Adding a twist to Alphii answer, actually the for loop would be second best and about 6 times slower than map

    from functools import reduce
    import datetime
    
    
    def time_it(func, numbers, *args):
        start_t = datetime.datetime.now()
        for i in range(numbers):
            func(args[0])
        print (datetime.datetime.now()-start_t)
    
    def square_sum1(numbers):
        return reduce(lambda sum, next: sum+next**2, numbers, 0)
    
    
    def square_sum2(numbers):
        a = 0
        for i in numbers:
            a += i**2
        return a
    
    def square_sum3(numbers):
        a = 0
        map(lambda x: a+x**2, numbers)
        return a
    
    def square_sum4(numbers):
        a = 0
        return [a+i**2 for i in numbers]
    
    time_it(square_sum1, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
    time_it(square_sum2, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
    time_it(square_sum3, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
    time_it(square_sum4, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
    

    Main changes have been to eliminate the slow sum calls, as well as the probably unnecessary int() in the last case. Putting the for loop and map in the same terms makes it quite fact, actually. Remember that lambdas are functional concepts and theoretically shouldn't have side effects, but, well, they can have side effects like adding to a. Results in this case with Python 3.6.1, Ubuntu 14.04, Intel(R) Core(TM) i7-4770 CPU @ 3.40GHz

    0:00:00.257703 #Reduce
    0:00:00.184898 #For loop
    0:00:00.031718 #Map
    0:00:00.212699 #List comprehension
    

提交回复
热议问题