Operator overloading is much slower than a method call?

Scott Harris scottrharris at earthlink.net
Mon Apr 29 12:51:33 EDT 2002


I did some simple timing experiments last night that seem to indicate that
operator overloading is about 35% slower than a method call on an object.

Here's what I was doing:

I have a class Vector that implements standard 3-vector operations like
dot products and additions, etc...

If a and b are vectors, I can write

c=a.add(b) #approach 1
  
or 

c=a+b #approach 2

where the overloaded + operator simply calls the add method.

Anyhow, I find that second approach is about 35% slower on my machine than the
direct method call.


I timed this by doing about 60K vector additions with the only change being
the direct call to the method versus the operator approach.

I'm pretty suprised by these results. I had only expected a slight performance
hit. Since my code makes pretty extensive use of overloading for readability
I guess I'm taking a big hit.

Is this a well known result? Is there anything that can be done about it?
Is operator overloading really that much more work for the interpreter to
figure out?

Comments would be appreciated.

I'm using python2.2 on Linux. 

Thanks,
-Scott Harris
scottrharris.earthlink.net



More information about the Python-list mailing list