飄逸的python,飄逸python

來源:互聯網
上載者:User

飄逸的python,飄逸python
dis — Disassembler for Python bytecode,即把python代碼反組譯碼為位元組碼指令.
使用超級簡單:python -m dis xxx.py

當我在網上看到while 1比while True快的時候,我感到很困惑,為何會有這種區別呢?

於是使用dis來深入.


假設est_while.py代碼如下.

#coding=utf-8while 1:    passwhile True:    pass

下面是使用dis來進行剖析.

E:\>python -m dis test_while.py  2           0 SETUP_LOOP               3 (to 6)  3     >>    3 JUMP_ABSOLUTE            3  5     >>    6 SETUP_LOOP              10 (to 19)        >>    9 LOAD_NAME                0 (True)             12 POP_JUMP_IF_FALSE       18


根據python官方文檔,dis輸出報告的格式如下.

The output is divided in the following columns:

The parameter interpretation recognizes local and global variable names, constant values, branch targets, and compare operators.


可以看到,在while 1這裡(第3行),直接是JUMP_ABSOLUTE指令;

而while True這裡(第5行),由LOAD_NAME和POP_JUMP_IF_FALSE指令組成.


原來True在python2中不是一個關鍵字,只是一個內建的變數,bool類型,值為1,即True+True輸出2.
而且還可以被賦值.比如賦值True = 2, 甚至可以賦值True = False.

所以while True的時候, 每次迴圈都要檢查True的值, 對應指令LOAD_NAME.

這就是為什麼while True比while 1慢了.


不過在python3中,True變成了關鍵字了.while 1和while True的指令相同,所以沒有效能區別了.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.