Creating bodies faster?

Topics: Developer Forum
May 7, 2011 at 9:26 AM
Edited May 7, 2011 at 9:58 AM

The game I'm currently working on creates/deletes a lot of bodies fairly regularly and after some performance profiling I've found that this is the bottleneck keeping the game from running at 30fps on WP7 devices. Every meteor and every missile is a sphere body created as the body is being created, so as you can no doubt tell there's a lot of bodies being created/deleted very rapidly.

Is there a way I can optimize past this or do I have to bite the bullet and pre-make all the bodies and set them as I need them?

 

There's something interesting I found too, the way I was profiling the speed was with the following code:

 

watch.Start();

for(int i = 0; i < 10; i++)
{

CreateSphere();
}

 

watch.Stop();

 

DeleteCreatedSpheres();

 

in the update routine and the delay the stopwatch was reporting was going down, so it would say a delay of 500ms, then a delay of 200ms, then a delay of 100ms then a delay of 10ms, then a delay of 500ms (etc, etc).

Any reason for this (I suspect it's the garbage collector)?

May 7, 2011 at 4:47 PM
Edited May 7, 2011 at 4:47 PM

Hi,

 I'm not an expert on performance with Farseer, so I'll let someone else answer that. However, do you know what the maximum number of meteors there will be on screen at any given time? You might find it faster if you create a pool of type 'Meteor'. When one is destroyed, simply return it back to the pool instead of deleting it. If more are on screen than expected, you could create it as you currently are. By reusing the meteors, you also minimise any garbage collection.

May 11, 2011 at 7:00 AM
Edited May 11, 2011 at 7:13 AM

Like keyboardP said, I think your best bet is to create the objects only once and reuse them. Rather than creating new objects every time, you can add a reset() method that returns the objects to their original positions and/or adds them to a collection (popped off a stack?) to be used again.

Edit: After reading the documentation for 2.1, if you look under Performance, point 5 describes exactly the situation you're asking about and keyboardP is saying. :-)

May 11, 2011 at 7:00 AM
Edited May 11, 2011 at 7:00 AM

-- Accidental double post. Delete. --

May 11, 2011 at 8:27 PM

Thanks Drackir, that's a great link! Had no idea Farseer already had a public Pool system implemented.

May 13, 2011 at 12:51 AM

That's a great article! Now I just need to figure out how to implement it abstractally for my physics wrapper class :P

May 13, 2011 at 4:47 PM

One thing to note is that is old documentation, but the core of what it says is still useful.

When it speaks of geometries, that is what is currently called fixtures in the latest code.