What can I do to improve performance of this function? So far I've changed stuff as local as possible and made a break
if all possible surrounding tiles have been found. Also I use a separate variable to track the length of a list instead of len()
.
The usage of this is to find surrounding tiles for all tiles.
def getsurroundings(tiles):
for t in tiles:
currentrect = Rect(t.rect[0] - t.rect[2] / 2, t.rect[1] - t.rect[3] / 2, t.rect[2] * 2, t.rect[3] * 2)
check = currentrect.colliderect
surroundings = t.surroundings
append = t.surroundings.append
surroundingscount = t.surroundingscount
for t2 in tiles:
if check(t2.rect) and not t == t2 and not t2 in surroundings:
append(t2)
t2.surroundings.append(t)
surroundingscount+=1
t2.surroundingscount+=1
if surroundingscount == 8:
break
return tiles
Here's the code without localisations which might be easier to read:
def getsurroundings(tiles):
for t in tiles:
currentrect = Rect(t.rect[0] - t.rect[2] / 2, t.rect[1] - t.rect[3] / 2, t.rect[2] * 2, t.rect[3] * 2)
for t2 in tiles:
if currentrect.colliderect(t2.rect) and not t == t2 and not t2 in t.surroundings:
t.surroundings.append(t2)
t2.surroundings.append(t)
t.surroundingscount+=1
t2.surroundingscount+=1
if t.surroundingscount == 8:
break
return tiles
EDIT
I wrote the following, which is around 10x faster than the original one.
Where width
is the width of the map, and height
is the height of the map.
Tiles are appended to the tiles
list first from right to left and then from bottom to up.
for t in tiles:
index = tiles.index(t)
if index > width - 1:
t.surroundings.append(tiles[index - width])
if not index % width == width - 1:
t.surroundings.append(tiles[index - width + 1])
if not index % width == 0:
t.surroundings.append(tiles[index - width - 1])
if not index % width == width - 1:
t.surroundings.append(tiles[index + 1])
if not index % width == 0:
t.surroundings.append(tiles[index - 1])
if index < width * height - width:
t.surroundings.append(tiles[index + width])
if not index % width == width - 1:
t.surroundings.append(tiles[index + width + 1])
if not index % width == 0:
t.surroundings.append(tiles[index + width - 1])
Thanks for help everyone! I would check all the answers accepted if I could.