Recently, I had to complete a task that used many operations with coordinates. Thinking to save time and simplify my code, I defined a class for encapsulating the behavior of a pair of coordinates. The class looked like this:
class Vector (tuple) : def __init__ (self, value) : tuple.__init__ (self, value) def __add__ (self, other) : return Vector ((self [0] + other [0], self [1] + other [1]))
This allowed me to write code like this (for example):
def translate (pointList, displacement) : return [point + displacement for point in pointList]
But my application was terribly slow. Much slower than other tasks. I could not find any inefficiency in my implementation of the algorithm, so I did a simple test to find out what the overhead of the Vector class is. I was expecting somewhere between 5% and 15%.
My Vector class test looked like this:
v = Vector ((0, 0)) d = Vector ((1, -1)) loopIdx = 3000000 while loopIdx > 0 : v = v + d loopIdx -= 1 print (v)
This executes (usually) at this type of time:
real 0m8.440s user 0m8.367s sys 0m0.016s
For comparison, I ran this code:
v = (0, 0) dX = 1 dY = -1 loopIdx = 3000000 while loopIdx > 0 : v = ( v [0] + dX, v [1] + dY ) loopIdx -= 1 print (v)
Runtime for this code:
real 0m1.004s user 0m0.995s sys 0m0.006s
Am I doing something serious wrong, or does using class objects in Python really mean that your application will take 8 times as long?