Welcome to the sixth part of the particle engine tutorial today we will be optimizing our code to run faster. If you have been following along you will remember the graph in the last tutorial were our particles took up 54% of the memory after only a minute. After the adjustments we will compare our new graph with our old graph. First thing we have to do is get rid of that nasty list in our particle engine and replace it will an array and queue.Now the goal of using an array and queue is to take a particle from our free particles queue and enable it within our array. This is going to change how we create our particles so lets change that first. The particles constructor will no longer set all the properties instead we will create a new method named Initialize to do that.
Basically just take our constructor code and cut it into a new method were we also set is alive to true.
Next were going to change our particle engine constructor slightly since it will not be loading in the list any more instead we will do all that a new method called Initialize again. The reason we can't do this stuff in the constructor is because the values need are not set until after the constructor is completed.
Enqueue is essentially the same ass Add for a list. We want to fill our free particles queue with particles because in the beginning all the particles will be free. Next were going to do some touch ups to convert from using a list to a queue / array. Instead of adding in a particle when its time we are now taking a particle from the free particles queue and initializing it with our position. Dequeue returns the first object of the queue while also removing it from the queue. This is all good except that were missing the Initialize Particle method so lets create that now.
This method is very similar to our old method for adding particles to our list. Only difference is that were not returning a particle were instead just turning an old particle back on.
Now our draw method is slightly different as well. Because the values in our array do not represent when they were creating were now just going to draw them in order using a for each loop.
One last step, after we load all of our variables for the particle engine in the game1 class we now have to call Initialize to load in our stuff.Now that we have done that we can run our game. Depending on the settings of your game 1 class it might look slightly different. Now lets compare our memory usage with the old settings of 500 particles per second for 1 to 2 second life time. With our old method we had a 54% memory usage for the particles. Now with the new method we only have a 4% usage. That is about 13 times better with only minor changes.
There are only a few more changes planned so if you have any ideas or suggestions for another tutorial post a comment.
You are free to use or modify this source in any way it is for learning purposes