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

后端 未结 7 1431
梦如初夏
梦如初夏 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:22

    I wrote a simple script that test the speed and this is what I found out. Actually for loop was fastest in my case. That really suprised me, check out bellow (was calculating sum of squares).

    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:
            i = i**2
            a += i
        return a
    
    def square_sum3(numbers):
        sqrt = lambda x: x**2
        return sum(map(sqrt, numbers))
    
    def square_sum4(numbers):
        return(sum([int(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])
    
    0:00:00.302000 #Reduce
    0:00:00.144000 #For loop
    0:00:00.318000 #Map
    0:00:00.390000 #List comprehension
    

提交回复
热议问题