-1

Is there a difference in performance between these two examples:

Example 1:

class Calculator:
    def add(self, a, b):
        return a+b
import Calculator

calc = Calculator()
print(calc.add(1, 2))

Example 2:

def add(a, b)
    return a+b
from Calculator import add

print(add(1, 2))

Am i going to have performance issues with going for classes instead of imported functions? Considering Multithreading and Multiprocessing.

  • 2
    Deciding to use a function or a class shouldnt take performance into account (almost all of the time) – Sayse May 06 '21 at 10:06
  • I think there won;t be.. You can check this question asked on Java (I know you're using python but why not ) - https://stackoverflow.com/questions/7128348/performance-difference-between-a-wild-card-import-and-the-required-class-import – Rush W. May 06 '21 at 10:06
  • Yes, there is, but that should not be the driving question: There is just no point in making ``add`` a method in some class – there is no instance-specific state used. On the other hand, when you need instance-specific state then a function is not appropriate. Which one is slower is hardly relevant; use whatever abstractions you need, don't use whatever abstractions you don't need. – MisterMiyagi May 06 '21 at 10:09
  • Sure there is no need to do it with an add method. (This should be just a simple example) But you get the advantage to write tests for your classes. – DonyThePony May 06 '21 at 10:13
  • 1
    You can also write tests for functions, so I don't see how that is relevant. – MisterMiyagi May 06 '21 at 10:21
  • 2
    There is no point guessing the performance of useless and hypothetical code. If you care about performance, make sure that measuring performance becomes part of your development habits, like testing is part of test-driven development. – Ulrich Eckhardt May 06 '21 at 10:25

1 Answers1

0

I have done some tests and it seems to be a small difference of about ~6% but if speed is a concern try using numpy or something similar or dont use python (or any other scripting language) at all.

Isotope
  • 141
  • 1
  • 5
  • 16