why is a[1] fast than a.get
(1)
果凍
why is a[1] fast than a.get(1)
import timeit
print timeit.timeit('a={1:1};a.get(1)',
number=10000)
print timeit.timeit('a={1:1};a[1]', number=10000)
Let we see opcode
def func():
a = {1:1}
a[1]
a.get(1)
import dis
dis.dis(func)
a[1]
3 13 LOAD_FAST 0 (a)
16 LOAD_CONST 1 (1)
19 BINARY_SUBSCR
20 POP_TOP
use
BINARY_SUBSCR
a.get(1)
4 21 LOAD_FAST 0 (a)
24 LOAD_ATTR 0 (get)
27 LOAD_CONST 1 (1)
30 CALL_FUNCTION 1
33 POP_TOP use
CALL_FUNCTION
Let we see python implementation, a
[1]
Call the function.
PyObject_GetItem
Call the function.
dict_subscript
Let we see python implementation,
a.get(1)
Call the function.
call_function at Python/ceval.c
● The function is too long. Hard to put code
here.
● some code in call_function
PyCFunction_Call at
Objects/methodobject.c
● Another longer function.
● The function will call dict_get(at
Object/dictobject.c)
Unpack argument first.
Another longer function.
PyArg_UnpackTuple
● Another longer function.
● Python/getargs.c
Summary
● This is why a[1] is fast than a.get(1)
○ a.get(1) do more thing than a[1]
● what about a.__getitem__ ?
○ The opcode is CALL_FUNCTION. slower.
○ But it call dict_subscript instead of dict_get. fast.
○ a[1] is fast than a.__getitem__(1). And a.
__getitem__(1) is fast than a.get(1)

Why is a[1] fast than a.get(1)