Python中 not not x 与 bool(x) 的性能差异解析

Ivy
Ivy
发布时间:2026-10-15| 3人浏览过
原创

本文对比了Python中 not not x 与 bool(x) 两种布尔转换方式。通过百万次测试发现,not not x 执行更快,因其仅涉及单条指令,而 bool(x) 涉及函数调用开销。尽管 not not x 性能更优,但出于代码可读性考虑,仍推荐日常使用 bool(x)。

not not x 与 bool(x) 的基本转换

这两种方式均能将变量 x 转换为布尔类型。


>>> x = 123
>>> not not x
True
>>> bool(x)
True
>>>


性能测试对比

那么,哪一种执行效率更高呢?我们可以通过编写测试代码,执行 100 万次循环来对比两者的性能:


import timeit


def bool_convert(x):
    return bool(x)


def notnot_convert(x):
    return not not x


def main():
    trials = 10_000_000
    kwargs = {
        "setup": "x=42",
        "globals": globals(),
        "number": trials,
    }

    notnot_time = timeit.timeit("notnot_convert(x)", **kwargs)
    bool_time = timeit.timeit("bool_convert(x)", **kwargs)

    print(f"{bool_time = :.04f}")
    print(f"{notnot_time = :.04f}")


if __name__ == "__main__":
    main()

具体的运行结果如下所示:

字节码差异分析

实际上,bool(x) 较慢的原因在于它是一个函数调用过程,而 not not x 仅仅是一条指令,拥有更直接的布尔值转换路径。这一点可以通过查看字节码得到验证:

可以看到,bool(x) 额外包含了 LOAD_GLOBAL 和 CALL_FUNCTION 操作。

此处附上相关的官方字节码说明:


LOAD_GLOBAL(namei)
Loads the global named co_names[namei] onto the stack.

CALL_FUNCTION(argc)
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.

UNARY_NOT
Implements TOS = not TOS.


总结来说:

性能差异原因详解

从测试结果来看,not not x 比 bool(x) 的速度更快。主要原因在于 bool(x) 是一个函数调用,函数调用需要将参数压入栈顶。栈顶包含位置参数,最右侧的参数位于栈顶,其下方是要调用的可调用对象。CALL_FUNCTION 需要从堆栈中弹出所有参数和可调用对象,使用这些参数调用该对象,并将返回值推入堆栈。这一系列过程比执行一条 not 指令要慢得多。

开发建议

不过,我仍然推荐你使用 bool(x) ,因为它的可读性更高。此外,在实际开发中,我们也不太可能调用它 100 万次。

到此这篇关于 python 中 not not x 与 bool(x) 的区别的文章就介绍到这了,更多相关 not not x 与 bool(x) 的区别内容请搜索本站以前的文章或继续浏览下面的相关文章,希望大家以后多多支持本站!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。