title: Overhead of creating classes in Python: Exact same code using class twice as slow as native DS?
body: <p>I created a Stack class as an exercise in Python, using all list functions. For example, Stack.push() is just list.append(), Stack.pop() is list.pop() and Stack.isEmpty() is just list == [ ].</p>
  
  <p>I was using my Stack class to implement a decimal to binary converter, and what I noticed is that even though the two functions are completely equivalent beyond the wrapping of my Stack class for push(), pop() and isEmpty(), the implementation using the Stack class is twice as slow as the implementation using Python's list.</p>
  
  <p>Is that because there's always an inherent overhead to using classes in Python? And if so, where does the overhead come from technically speaking ("under the hood")? Finally, if the overhead is so significant, isn't it better not to use classes unless you absolutely have to?</p>
  
  <pre><code>def dectobin1(num):
      s = Stack()
      while num &gt; 0:
          s.push(num % 2)
          num = num // 2
      binnum = ''
      while not s.isEmpty():
          binnum = binnum + str(s.pop())
      return binnum
  
  def dectobin2(num):
      l = []
      while num &gt; 0:
          l.append(num % 2)
          num = num // 2
      binnum = ''
      while not l == []:
          binnum = binnum + str(l.pop())
      return binnum
  
  
  t1 = Timer('dectobin1(255)', 'from __main__ import dectobin1')
  print(t1.timeit(number = 1000))
  
  0.0211110115051
  
  t2 = Timer('dectobin2(255)', 'from __main__ import dectobin2')
  print(t2.timeit(number = 1000))
  
  0.0094211101532
  </code></pre>