This check for if some points are inside a rectangle, and whenever it’s run it slows my program down a lot. How can we change it to make it more efficient?
def draw_grid(self, box):
for element in self.map_layout.all_map_objects:
if element not in self.build_grid and box.area.collidepoint(element.checkpoint):
self.build_grid.append(element)
elif not box.area.collidepoint(element.checkpoint):
if element in self.build_grid:
self.build_grid.remove(element)
One change which is trivial to make is to store the result of
box.area.collidepoint:Other changes rely on the data structure that you need. For example,
self.build_gridseems to be alist.__contains__(in operator) on a list is an O(N) operation on average whereas if you could get by with aset, it would be O(1)!. The same thing goes withlist.remove— Here you could use atry-exceptclause to remove one O(N) operation from the tight loop which might help if the element is usually in the list: