Not not x 和 Bool(x) 用哪个比较好?

开发 前端
从结果来看,not not x 比 bool(x) 更快,主要原因在于 bool(x) 是一个函数调用,函数调用需要参数压入栈顶,堆栈的顶部包含位置参数,最右边的参数在顶部,参数下面是要调用的可调用对象。

[[434453]]

今天来做一个选择,就是 not not x 和 bool(x) 用哪个比较好?

他们都可以把 x 变成一个布尔类型的值:

  1. >>> x = 123 
  2. >>> not not x 
  3. True 
  4. >>> bool(x) 
  5. True 
  6. >>> 

那么谁更快呢?我们写段代码,跑个 100 万次,来比较下谁更快:

  1. import timeit 
  2.  
  3.  
  4. def bool_convert(x): 
  5.     return bool(x) 
  6.  
  7.  
  8. def notnot_convert(x): 
  9.     return not not x 
  10.  
  11.  
  12. def main(): 
  13.     trials = 10_000_000 
  14.     kwargs = { 
  15.         "setup""x=42"
  16.         "globals": globals(), 
  17.         "number": trials, 
  18.     } 
  19.  
  20.     notnot_time = timeit.timeit("notnot_convert(x)", **kwargs) 
  21.     bool_time = timeit.timeit("bool_convert(x)", **kwargs) 
  22.  
  23.     print(f"{bool_time = :.04f}"
  24.     print(f"{notnot_time = :.04f}"
  25.  
  26.  
  27. if __name__ == "__main__"
  28.     main() 

运行结果如下:

其实 bool(x) 慢的原因在于它是一个函数调用,而 not not x 就是一条指令,具有更快捷的转换为布尔值的路径,这一点可以从字节码可以看出来:

bool(x) 多了 LOAD_GLOBAL 和 CALL_FUNCTION。

这里附一下相关字节码的官方说明:

  1. LOAD_GLOBAL(namei) 
  2. Loads the global named co_names[namei] onto the stack. 
  3.  
  4. CALL_FUNCTION(argc) 
  5. Calls a callable object with positional arguments. argc indicates the number of positional arguments. The top of the stack contains positional arguments, with the right-most argument on top. Below the arguments is a callable object to call. CALL_FUNCTION pops all arguments and the callable object off the stack, calls the callable object with those arguments, and pushes the return value returned by the callable object. 
  6.  
  7. UNARY_NOT 
  8. Implements TOS = not TOS. 

最后

从结果来看,not not x 比 bool(x) 更快,主要原因在于 bool(x) 是一个函数调用,函数调用需要参数压入栈顶,堆栈的顶部包含位置参数,最右边的参数在顶部,参数下面是要调用的可调用对象。CALL_FUNCTION 从堆栈中弹出所有参数和可调用对象,使用这些参数调用可调用对象,并推送可调用对象返回的返回值,这一过程比一个 not 指令要慢得多。 

不过我仍然推荐你使用 bool(x),因为它的可读性更高,而且,你也不太可能调用它 100万次。

 

责任编辑:武晓燕 来源: Python七号
相关推荐

2021-11-05 07:13:46

Python

2021-11-30 23:01:51

编程语言数据Python

2009-09-15 09:24:42

思科认证考试思科认证

2021-08-05 08:32:45

TypeScript InterfaceType

2020-09-23 16:53:46

Python编辑器工具

2018-06-16 14:32:16

无线路由器单频双频

2021-03-15 14:09:49

电脑软件安全

2010-03-29 17:38:18

CentOS源代码

2020-01-17 13:33:42

大数据分析师大数据工程师

2011-10-26 20:34:24

ssh 客户端

2020-07-28 10:40:26

大数据专业技术

2020-11-18 09:26:52

@property装饰器代码

2020-12-08 15:54:15

编程语言Python

2015-01-08 22:06:18

2020-06-30 09:10:35

编程学习技术

2022-06-06 15:06:42

MySQLJAVA

2023-04-27 07:26:31

IP地址无符号

2014-06-05 15:16:49

Linux开源Flash

2018-12-17 13:03:39

AI数据科技

2022-03-13 23:31:13

JavaScript工具动画库
点赞
收藏

51CTO技术栈公众号