python中关于if-else使用性能的一点感悟


今天做leetcode第7题关于数字倒序的问题,分别使用如下程序:(72ms)

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        #maxNum = 2**31-1
        #minNum = -1*2**31
        i = 1
        if(x<0):
            i,x = -1,abs(x)
        x_s = str(x) 
        x_s = i*int(x_s[::-1])
        if x_s >2147483647 or x_s < -2147483648:
            return 0
        return x_s

  

而使用方法2:(112ms)

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        #maxNum = 2**31-1
        #minNum = -1*2**31
        i = 1
        if(x<0):
            i,x = -1,abs(x)
        x_s = str(x) 
        x_s = i*int(x_s[::-1])
        
        return 0 if x_s >2147483647 or x_s < -2147483648 else x_s

  

在做一下改进:(76ms)

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        #maxNum = 2**31-1
        #minNum = -1*2**31
        i = 1
        if(x<0):
            i,x = -1,abs(x)
        x_s = str(x) 
        x_s = i*int(x_s[::-1])
        
        return x_s if x_s <= 2147483647 and x_s >= -2147483648 else 0
        #return 0 if x_s >2147483647 or x_s < -2147483648 else x_s

  

 

对比三种方法,可以看到,其实简简单单的一个if else,也有需要我们仔细考虑的:

第2种方法用时大,是因为用例大多数都是else中的内容,这样的话,大部分用例都执行完if又执行的else,这样的话,有一个if 为False之后的跳转过程,导致开销变大。

对于第3种方法,比第二种方法效率高的原因是:大部分用例都只执行到if阶段

而第1种方法和第3种方法对比,在于第1种方法使用的是 or ,对于 or 判决,如果第一个为真就满足了,可以缩小一些开销吧;

而第1种方法和第2种方法比,同样也是因为第2种方法else的跳转导致的。

 

总结就是:使用if-return-return 比 if-else-return更有效率一些。

 

参考:‘

https://stackoverflow.com/questions/9191388/it-is-more-efficient-to-use-if-return-return-or-if-else-return


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM