I did this in my previous game Space Bugs Wars where I had thousands of enemies and many hundreds bullets around on each frame, let me show you some code
List<BulletParticle> bulletFree = new List<BulletParticle>();
List<BulletParticle> bulletInUse = new List<BulletParticle>();
I had a class BulletParticle for example, it had the typical Update, Draw methods like:
public virtual void Update( GameTime gameTime ) {
// update code here, where I can check collisions and other things
}
public virtual void Draw( SpriteBatch spriteBatch ) {
// standard draw logic here
}
so, whenever I needed a new bullet, instead of doing
BulletParticle = new BulletParticle();
I did something like this
if (bulletFree.Count > 0 ) {
BulletParticle bullet = bulletFree[0];
bulletFree.RemoveAt(0);
bulletInUse.Add(bullet);
bullet.Reset( < insert your parameters here like position, speed, etc.. > );
}
}
and whenever I need to update the bullet I just did , this will free the bullet if it is dead , removing it from the bulletInUse list into the free list of bullets:
for ( int idx = bulletInUse.Count - 1; idx >= 0; idx-- ) {
BulletParticle bp = bulletInUse[idx];
bp.Update( elapsed );
if ( bp.IsDead ) {
bulletFree.Add( bp );
bulletInUse.RemoveAt( idx );
}
}
And you will need to add a bunch of free bullets when starting your game for the first time like
for ( int idx =0 ; idx<500; idx++){
BulletParticle bullet = new BulletParticle();
bulletFree.add(bullet);
}
So during gameplay, I never do a “= new Something()” , because that may be trashed later when you don’t need it anymore, so instead moved to a free list of that object type so I can re-use it multiple times like the bullets here. That saves a lot of time since allocation and garbage collection take too much time, so instead of doing cleaning , just recycle it. I do the same logic with enemies, bullets, power ups, pick ups , pretty much everything, and when I restart the game for a second play or more, you need to always move all the items from the used list into the free list. So you start the 2nd or 3rd or more rounds from zero without creating additional garbage.
Also if you think you may need more bullets you can add "= new … " into the free buffer, but you need to make sure you have enough memory, or limit the number of items in each list if you want to make sure you don’t go over the hardware limits, usually you will never have more than 200 or 300 of each type of thing but it depends on your game. In Space Bugs Wars I had 1500 enemies and I ran at 144 FPS (sync to my monitor refresh rate) without any issues and about 500 bullets at all times, with more than 2000 enemies I had some issues sometimes going to 100 FPS or less, so just to make sure it may work in more computers I pull down the number of enemies per frame.