Consider the following two naive implementations of 3D static vectors in Python:
class Vec1(tuple):
def __new__(c,x,y,z):
return super().__new__(c,(x,y,z))
def __add__(s,o):
return s.__class__(s[0]+o[0],s[1]+o[1],s[2]+o[2])
def __matmul__(s,o):
return s[0]*o[0]+s[1]*o[1]+s[2]*o[2]
class Vec2:
def __init__(s,x,y,z):
s.c=(x,y,z)
def __add__(s,o):
sc=s.c
oc=o.c
return Vec2(sc[0]+oc[0],sc[1]+oc[1],sc[2]+oc[2])
def __matmul__(s,o):
sc=s.c
oc=o.c
return sc[0]*oc[0]+sc[1]*oc[1]+sc[2]*oc[2]
A clean implementation is Vec1
which inherits methods from tuple
. However, the initialization of Vec1
(and, consequently, addition __add__
) is 1.5 times slower than that of Vec2
(on my machine). I suppose, the reason for this is the call of tuple.__new__()
. I’m aware that the initialization is still very fast (a fraction of a microsecond) and that I can improve the performance using Cython, Numba, or PyPy. But I’m interested in the question of how far I can get without using any third-party modules. Is it possible to initialize a Vec1
instance some other way? E.g. by directly writing to the memory location of the tuple elements?
4