所以我一直在研究 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__
方法。这比较慢。
例如,此类可以重写 %s
和 format()
,但不能重写 %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/