DEV Community

Discussion on: Inheritance in Python

Collapse
 
habilain profile image
David Griffin • Edited

While I was referring to best practices in programming (and remember, Python's style guide explicitly states where imports should go), with the view that best practice is absolutely something we should follow while teaching newcomers, the claim of performance being identical is demonstrably false.

import timeit
import string # warmup this to avoid any potential bias

def func_a():
  import string
  for x in range(10000):
      x += 1  # dummy operation so the loop does something we can compare against

def func_b():
  import string
  f = lambda x: x + 1
  for x in range(10000):
      f(x)

def func_c():
  for x in range(10000):
    import string

# Measurements on my laptop, an ageing i7-4500u, but trends should be reproducible
timeit.timeit('func_a()', globals=globals(), number=100) # Gives ~= 0.068
timeit.timeit('func_b()', globals=globals(), number=100) # Gives ~= 0.126
timeit.timeit('func_c()', globals=globals(), number=100) # Gives ~= 0.368
Enter fullscreen mode Exit fullscreen mode

So, point of fact, import is actually a pretty expensive operation; it's 6 times more expensive than simple bytecode ops, and three times more expensive than a function call.

Thread Thread
 
arsho profile image
Ahmedur Rahman Shovon

Updated the post to follow the best practices. Thank you a lot for pointing out those. Really appreciate your explanation and effort.