为什么实现 startwith
比切片慢?
In [1]: x = 'foobar'
In [2]: y = 'foo'
In [3]: %timeit x.startswith(y)
1000000 loops, best of 3: 321 ns per loop
In [4]: %timeit x[:3] == y
10000000 loops, best of 3: 164 ns per loop
令人惊讶的是,即使包括长度计算在内,切片仍然明显更快:
In [5]: %timeit x[:len(y)] == y
1000000 loops, best of 3: 251 ns per loop
注意:这种行为的第一部分在Python数据分析(第三章)中有提到,但没有解释。
.
如果有帮助的话:这里是startswith
的C代码;以及dis.dis
的输出结果:
In [6]: import dis
In [7]: dis_it = lambda x: dis.dis(compile(x, '<none>', 'eval'))
In [8]: dis_it('x[:3]==y')
1 0 LOAD_NAME 0 (x)
3 LOAD_CONST 0 (3)
6 SLICE+2
7 LOAD_NAME 1 (y)
10 COMPARE_OP 2 (==)
13 RETURN_VALUE
In [9]: dis_it('x.startswith(y)')
1 0 LOAD_NAME 0 (x)
3 LOAD_ATTR 1 (startswith)
6 LOAD_NAME 2 (y)
9 CALL_FUNCTION 1
12 RETURN_VALUE
startswith
,你也可以传递start
和end
参数,但要注意这需要一些时间来处理。 - SilentGhost