Search code examples
python-3.xoptimizationmaxcompiler-optimization

The running speed differences between for loop and max in Python3


I never noticed that there is a difference on running speed between for and max() in Python3 until I solved a Leetcode problem(718) and got TLE. Here is my code:

class Solution:
    def findLength(self, nums1: List[int], nums2: List[int]) -> int:
        n = len(nums1)
        m = len(nums2)
        res = 0
        dp = [[0]*(m+1) for i in range(n+1)]
        # dp[i][j] means the max length of both subarray ends at nums1[i] and nums2[j]
        for i in range(1,n+1):
            for j in range(1, m+1):
                if(nums1[i-1] == nums2[j-1]):
                    dp[i][j] = dp[i-1][j-1] + 1
        
        # using max, pass
        return max(max(each) for each in dp)
        
        # using for loops, TLE
        # for i in range(1, n+1):
        #     for j in range(1, m+1):
        #         res = max(dp[i][j], res)
        # return res

As I point out, using for loops to get the maximum value in 2D array dp, I got a TLE with over 9500ms - 10000ms running time, and using max(max(each) for each in dp) to get the maximum value in 2D array dp can pass with 8000ms - 9000 ms.

Does anyone know why there is such a big difference between them?


Solution

  • It is true that the performance of 'list comprehension' is better than 'for loop' in python. See the article below, hope it could help. Are list-comprehensions and functional functions faster than "for loops"?