Search code examples
pythonoperatorsmagic-methods

Is using magic methods quicker than using operator in python?


I want to ask that is using magic methods( like int.__add__()) is quicker than using operators (like +) ?

will it make a difference even by a bit?

thanks.


Solution

  • Here is the disassembled byte code for 3 different ways of adding.

    import dis
    
    def add1(a, b):
        return a + b
    
    dis.dis(add1)
      2           0 LOAD_FAST                0 (a)
                  2 LOAD_FAST                1 (b)
                  4 BINARY_ADD
                  6 RETURN_VALUE
    
    def add2(a, b):
        return a.__add__(b)
    
    dis.dis(add2)
      2           0 LOAD_FAST                0 (a)
                  2 LOAD_ATTR                0 (__add__)
                  4 LOAD_FAST                1 (b)
                  6 CALL_FUNCTION            1
                  8 RETURN_VALUE
    
    def add3(a, b):
        return int.__add__(a, b)
    
    dis.dis(add3)
      2           0 LOAD_GLOBAL              0 (int)
                  2 LOAD_ATTR                1 (__add__)
                  4 LOAD_FAST                0 (a)
                  6 LOAD_FAST                1 (b)
                  8 CALL_FUNCTION            2
                 10 RETURN_VALUE
    

    a+b generates the simplest byte code, but I expect that the interpreter's code for BINARY_ADD simply calls the first arguments's __add__() method, so it's effectively the same as a.__add__(b).

    int.__add__(a, b) looks like it might be faster because it doesn't have to find the method for a specific object, but looking up the int.__add__ attribute may be just as expensive.

    If you really want to find out which is best, I suggest you run benchmarks.