python代碼最佳化案例分析

來源:互聯網
上載者:User

標籤:python

第一版舉例:

def displayNumType(num):    print num,"is",    if type(num)==type(0):        print 'an interger'    elif type(num)==type(0L):        print 'a long'    elif type(num)==type(0.0):        print 'a float'    elif type(num)==type(0+0j):        print 'a complex number'    else:        print 'not a number at all!!'

最終版舉例:

def displayNumType(num):    print num,'is',    if isinstance(num,(int,long,float,complex)):        print 'a  number of type:',type(num).__name__    else:        print 'not a number at all!!'


最佳化思路:

1、減少函數調用的次數

在第一版代碼中,每次判斷會調用兩次type()。

  • 最佳化方式:

import typesif type(num)==types.IntType...


2、對象值比較 VS 對象身份比較

type(0),type(42)等都是同一個對象“<type 'Int'>”,沒有必要進行值得比較。因為每一個類型只有一個類型對象。

  • 最佳化方式:

if type(num) is types.IntType...  ##or type(0)


3、減少查詢次數

為了得到整數的物件類型,解譯器不得不首先尋找types這個模組的名字,然後在該模組的字典中尋找IntType。

通過使用from-import,可以減少一次查詢。

  • 最佳化方式:

from types import IntTypeif type(num) is IntType


4、慣例和代碼風格

isinstance()函數讓if語句更方便,並具有更好的可讀性。

  • 最佳化方式:

if isinstance(num,int)...


摘選自《python核心編程(第二版)》第四章P68

python代碼最佳化案例分析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.