I have made a Vector2i class with the __eq__ operator overloaded as shown below.
class Vector2i:
def __init__(self, x: int = 0, y: int = 0):
self.x: int = x
self.y: int = y
# (...)
def __eq__(self, other):
return self.x == other.x and self.y == other.y
# (...)
It appeared to be fine, when, suddenly, my code slowed down a lot. After running the Python profiler, I saw the overloaded operator was taking most of the time and seemed to be the cause of the slowdown.
I tired to replace the overloaded operator with a simple Python comparison in the parts of the code that were slow.
# Inside a for loop.
"""
if c.position != checkpos:
continue
"""
if c.position.x != checkpos.x or c.position.y != checkpos.y:
continue
Got the exact same result. The code slows down a lot in that comparison. What's wrong?
Solution
The profiler was not very accurate and this was not the part slowing the code down. It was the loops running the comparison code over and over again. I fixed the problem by using numpy for heavy array operations.