请务必了解,在 print("Two plus two = " + str(number)) 中,连接操作与 print 无关,并且发生在调用 print 之前。
让我们做一些计时:
from timeit import Timer
def with_concat():
print("Two plus two = " + str(4))
def no_concat():
print("Two plus two =", 4)
print(min(Timer(with_concat).repeat(100, 100)))
print(min(Timer(no_concat).repeat(100, 100)))
输出
0.0006760049999998685
0.0013034899999999627
反直觉(请参阅我对问题的评论,字符串连接可能很昂贵)连接示例实际上更快(2倍!)以可重现的方式。但为什么呢?
让我们检查字节码:
from dis import dis
def with_concat():
print("Two plus two = " + str(4))
def no_concat():
print("Two plus two =", 4)
dis(with_concat)
输出
0 LOAD_GLOBAL 0 (print)
2 LOAD_CONST 1 ('Two plus two = ')
4 LOAD_GLOBAL 1 (str)
6 LOAD_CONST 2 (4)
8 CALL_FUNCTION 1
10 BINARY_ADD
12 CALL_FUNCTION 1
14 POP_TOP
16 LOAD_CONST 0 (None)
18 RETURN_VALUE
虽然
dis(no_concat)
输出
0 LOAD_GLOBAL 0 (print)
2 LOAD_CONST 1 ('Two plus two =')
4 LOAD_CONST 2 (4)
6 CALL_FUNCTION 2
8 POP_TOP
10 LOAD_CONST 0 (None)
12 RETURN_VALUE
从字节码来看,no_concat 应该更快(更短、更简单的代码)。
延迟必须来自 C 源代码(至少在 CPython 的情况下)。
让我们看看相关的行:
static PyObject *
builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
{
.
.
.
for (i = 0; i < PyTuple_Size(args); i++) {
if (i > 0) {
if (sep == NULL)
err = PyFile_WriteString(" ", file);
else
err = PyFile_WriteObject(sep, file,
Py_PRINT_RAW);
if (err)
return NULL;
}
err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
Py_PRINT_RAW);
if (err)
return NULL;
}
.
.
.
}
在我看来,使用print(*args) 的开销似乎是由于对PyTuple_GetItem(args, i) 的重复调用,而使用它而不是print(a + lot + of + concatenated + strings) 的好处只有在连接字符串的数量足够大时才会出现使串联成为瓶颈(即比重复调用PyTuple_GetItem(args, i) 慢)。