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

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

    I have managed to modify some of @alpiii's code and discovered that List comprehension is a little faster than for loop. It might be caused by int(), it is not fair between list comprehension and for loop.

    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*next, numbers, 0)
    
    def square_sum2(numbers):
        a = []
        for i in numbers:
            a.append(i*2)
        a = sum(a)
        return a
    
    def square_sum3(numbers):
        sqrt = lambda x: x*x
        return sum(map(sqrt, numbers))
    
    def square_sum4(numbers):
        return(sum([i*i 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.101122 #Reduce
    
    0:00:00.089216 #For loop
    
    0:00:00.101532 #Map
    
    0:00:00.068916 #List comprehension
    

提交回复
热议问题