Peter Finlayson | 10 May 2012 16:13
Picon
Gravatar

Observations on collisions

Hi,

Recently, I did some benchmarking on the various ways to do Rect collision detections using Pygame. I
mentioned some of 
this on the IRC channel a couple weeks ago, and they said that some of you on this list may be interested.

In the past, I have always stored the location of my sprites in a ((x, y), (w, h)) tuple, in a .rect attribute,
because 
I knew Pygame would automatically convert these to Rects as needed. It occured to me that it may be more
efficient to 
instead store them as actual Rects, so I decided to do some testing.

I got some surprising results, so I did more testing, and here's what I found when colliding a single item
against 100 
items (with 100 000 interations):

a rect and a list of tuples                    1.12 seconds,    5.9x
a rect and a list of objects containg tuples   3.19 seconds,    16.9x
a rect and a list of rects                     0.19 seconds,    1.0x
a rect and a list of subclassed rects          1.00 seconds,    5.3x
a rect and a list of objects containing rects  2.19 seconds,    11.6x
a sprite and a group of sprites                1.70 seconds,    9.0x
a sprite and an ordered group of sprites       1.55 seconds,    8.2x

The fastest way to do collisions was to do a Rect.collidelistall(). The surprising thing to me was how much
slower my 
chosen method was (Storing tuple in the .rect attributes of my classes). Up to twenty times slower on some tests.

Other things I found interesting:

(Continue reading)


Gmane