HTML and CSS Reference
In-Depth Information
When a particle reaches the end of its life, you dereference the particle object by removing it from the particles array:
// This is the kind of code you want to avoid!
// not only we are creating garbage from dereferencing particles
// but also by splicing arrays.
for (i = 0; i < particles.length; i++) {
var particle = particles[i];
if( particle.life === 0 ){
// our particle reached the end of its life
// splicing like pushing should be avoided
particles.splice(i, 1);
i--;
}
else
demo.integrate( particle );
particle.life--;
}
The memory occupied by all discarded objects isn't freed as you dereference them, but later, when the garbage
collector (GC) decides to do it. That's when memory usage drops in Figure 3-1 .
The bad news is that during the garbage collection, the program is stopped for the time needed to complete the
task and only resumes when the GC has done its job. This may take a long time, especially on mobile, which may miss
several frames.
The result of leaving memory management to the GC is that the game performs badly for a period of time
whenever the garbage is to be collected.
To have a steady frame rate, you need to take care of memory management yourself and recycle dead particles
instead of throwing them away; this avoids memory churn and the garbage collection taxes that come with it.
Figure 3-3 illustrates what the memory usage looks like when recycling is turned on in the demo:
Figure 3-3. Memory usage climbs to 33.6MB and never goes down
You can see the memory usage climb when the number of particles per second is bumped from 60 to 60,000. But
memory usage is stable now that you are using an object pool. By managing the churn of memory objects, you are
avoiding the largest contributor to the occurrence of GC events, meaning that your game's performance is going to be
much more consistent; you won't see performance loss from garbage collection.
How to Make an Object Pool
The goal of a pool is to avoid memory churn by reusing objects instead of allocating and freeing them, thus improving
performance.
Object pools maintain a collection of reusable objects and track their usage. As you will see, object pools are easy
to build and only require a few modifications to your existing objects' classes.
 
Search WWH ::




Custom Search