Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

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

304 views

Published on

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

Published in: Technology
  • Be the first to comment

  • Be the first to like this

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

  1. 1. why is a[1] fast than a.get (1) 果凍
  2. 2. 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)
  3. 3. Let we see opcode def func(): a = {1:1} a[1] a.get(1) import dis dis.dis(func)
  4. 4. a[1] 3 13 LOAD_FAST 0 (a) 16 LOAD_CONST 1 (1) 19 BINARY_SUBSCR 20 POP_TOP use BINARY_SUBSCR
  5. 5. 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
  6. 6. Let we see python implementation, a [1] Call the function.
  7. 7. PyObject_GetItem Call the function.
  8. 8. dict_subscript
  9. 9. Let we see python implementation, a.get(1) Call the function.
  10. 10. call_function at Python/ceval.c ● The function is too long. Hard to put code here. ● some code in call_function
  11. 11. PyCFunction_Call at Objects/methodobject.c ● Another longer function. ● The function will call dict_get(at Object/dictobject.c)
  12. 12. Unpack argument first. Another longer function.
  13. 13. PyArg_UnpackTuple ● Another longer function. ● Python/getargs.c
  14. 14. 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)

×