PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

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

anonymity
anonymity 原创
2019-05-24 13:48:35 3782浏览

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

谷歌的风格指南和PEP-8都使用if x is not 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中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。