python - 为什么用 % 十六进制化字符串比用 f 字符串十六进制化更快?

标签 python performance python-3.x string-formatting python-3.6

所以我一直在研究 f 弦及其在不同场景下的速度比较。我遇到了 f 字符串速度较慢的情况。

编辑:x = 0

In[1]: %timeit f"{x:0128x}"
363 ns ± 1.69 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In[2]: %timeit '%0128x' % x
224 ns ± 1.37 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In[3]: %timeit f"{x:0128X}"
533 ns ± 22 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In[4]: %timeit "%0128X" % x
222 ns ± 0.408 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

为什么在这种情况下 f 字符串较慢,为什么 f 字符串的“X”比“x”慢得多?

最佳答案

使用 %x 的字符串插值(以及其他数字转换)不能重载,因此解释器可以快速执行它。

f-strings 与 format() 内置函数相同,它需要在对象上查找 __format__ 方法。这比较慢。

例如,此类可以重写 %sformat(),但不能重写 %x:

class myint(int):
    def __format__(self, spec):
        return "example"
    def __int__(self):
        return "example"
    def __str__(self):
        return "example"
    def __repr__(self):
        return "example"
>>> '%x' % myint()
'0'

在 CPython 实现中,将字符串大写,首先构建小写字符串,然后循环该字符串以更改大小写。

重写__str__,即使返回常量字符串,也会使%s%x慢,因为它涉及方法调用.

关于python - 为什么用 % 十六进制化字符串比用 f 字符串十六进制化更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46162402/

相关文章:

python - 将一年中的小数日转换为 Pandas 日期时间

python - Jupyter 笔记本 : 500 Internal Server Error

python - 使用生成器迭代 Mongo 中的大型集合

php - 加速 PHP 应用程序

python - 从字符串中删除尾随的特殊字符

python - 使用 QDataWidgetMapper 立即更改模型

python - 为同一 matplotlib 图例中的每一行设置不同的 `numpoints` 参数

ruby-on-rails - 在 Rails 中执行 BDD/TDD 的最快方法?

python - 如何提高Python在大数据集中的计算速度?

python - Travis CI 在 macOS 上找不到 python3