使用 if x is not None 還是if not x is None

anonymity
發布: 2019-05-24 13:48:35
原創
4117 人瀏覽過

使用 if x is not None 還是if not x is None呢?

Google的風格指南和PEP-8都使用if x is not None,那麼它們之間是否存在某種輕微的效能差異呢?

使用 if x is not None 還是if not x is None

透過測試發現沒有效能差異,因為它們編譯為相同的字節碼:

Python 2.6.2 (r262:71600, Apr 15 2009, 07:20:39)>>> import dis>>> def f(x):...    return x is not None...>>> dis.dis(f)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               0 (None)
              6 COMPARE_OP               9 (is not)
              9 RETURN_VALUE>>> def g(x):...   return not x is None...>>> dis.dis(g)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               0 (None)
              6 COMPARE_OP               9 (is not)
              9 RETURN_VALUE
登入後複製

但是在使用風格上,盡量避免not x is y。儘管編譯器總是將其視為not (x is y),但讀者可能會誤解構造為(not x) is y。所以if x is not y就沒有這些歧義。

以上是使用 if x is not None 還是if not x is None的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!