Monday, August 06, 2012

Making your JavaScript garbage friendly, as in high-performance, garbage-collector-friendly!

buildnewgames - High-Performance, Garbage-Collector-Friendly Code

16 milliseconds is not a lot of time. Try eating a hotdog that fast – though I swear I’ve seen our dog go through a beef sausage in under 100 milliseconds.

If you want your game to run at 60 frames per second, 16 milliseconds is all you have to get everything done: moving bullets around, creating new entities, drawing sprites, checking collisions, tracking and changing states, handling input and playing sound. Whatever happens regularly in the main game cycle needs to operate as efficiently as possible. Even at a lower-performing frame rate of 30 per second, you’ll still only have 32 milliseconds to get everything done. Speed and efficiency are important, and that importance increases over time as you add more things to your game.

What’s garbage collection, and why do I care?

If you’re developing a game that has many things happening at the same time, say a weapon that fires missiles 5 times per second – not an unreasonable weapon fire rate for a high-speed shooter – you’ll quickly discover that one area of substantial impact to performance is object construction and subsequent garbage collection.

As your classes grow in size, and possibly in complexity, you’ll begin to notice lag introduced when you construct something new; this is exacerbated if you’re doing complex setup of sprites and sounds (even if they are cached in static resources). Creating lots of objects also has the side effect of generating garbage collection.

For those new to the concept, JavaScript, like many other interpreted languages, frees you from having to manage memory; you can create objects at will, without really having to keep track. The browser (or to be more specific, the JavaScript Virtual Machine running inside the browser) will come along periodically and clean up anything you’re not using anymore. This part of the system is the garbage collector (GC) – you can think of it like the ultimate housemaid.

Depending on the browser, and number of objects you have in use, the process of garbage collection can take anywhere from 10ms to 2000ms. The more things it has to check to be cleaned, and the more cleaning it has to do, the longer it will take. If you’re writing a game with independently moving objects, like an action game, this pause is going to at best noticeable, or, at worst, a series of frustrating stalls that kills the experience.

Garbage-collector-friendly code

For the most part, it’s pretty easy to write code that makes life easy for the garbage collector. ...

image..."

Everyone is JS'ing these days, so making sure you GC well means your VM will have a high IO! :P

No comments: