Play the game at www.RainingChain.com.
Check the source code on Github.

Thursday, 12 February 2015

Try and Catch Performance Trap

I've recently started to optimize the code for Raining Chain. After using a profiler with Google Chrome, I realized that some functions had a triangle indicating that the Javascript V8 engine couldn't optimize them. Puzzled, I checked online and learned a bit more about the V8 optimizer.

Long story short, functions are optimized individually. It turns out that functions that contain a try and catch statement can not be optimized. This is a very big deal considering the V8 optimizer is what makes Javascript run fast. And obviously, when buidling a HTML5 MMORPG, performance is very important. After some JSPerf tests, I estimated that the try and catch slows down a function by a lot (x1.25 to x10 slower).

As an alternative, I create a dummy function that contains the try and catch that calls the real function. Doing so is a lot faster but also somewhat annoying to do. It is only worth doing if the function containing the try and catch has a considerable size, otherwise the extra call will nullify the gain from the optimizer.

//Before (slower)
a = function(){
    try {
     //Lots of stuff
    } catch(err){}; 
}

//After (faster)
b = function(){
    try {
     c();
    } catch(err){};
}
c = function(){
 //Lots of stuff
}

No comments:

Post a Comment