AJAX In Action [147]
/(dist*dist*gravF);
var xGrav=grav*(distX/dist);
var yGrav=grav*(distY/dist);
moon.physics.acc.x=-xGrav/(moon.physics.mass);
moon.physics.acc.y=-yGrav/(moon.physics.mass);
moon.physics.vel.x+=moon.physics.acc.x;
moon.physics.vel.y+=moon.physics.acc.y;
moon.physics.pos.x+=moon.physics.vel.x;
moon.physics.pos.y+=moon.physics.vel.y;
Licensed to jonathan zheng 298 CHAPTER 8 Performance This is something of a caricature—we’ve deliberately used as many deep references down the object graphs as possible, making for verbose and slow code. There is certainly plenty of room for improvement! Here’s the same code from the optimized version: var mp=moon.physics; var mpa=mp.acc; var mpv=mp.vel; var mpp=mp.pos; var mpm=mp.mass; ... var grav=(epm*mpm)/(dist*dist*gravF); var xGrav=grav*(distX/dist); var yGrav=grav*(distY/dist); mpa.x=-xGrav/(mpm); mpa.y=-yGrav/(mpm); mpv.x+=mpa.x; mpv.y+=mpa.y; mpp.x+=mpv.x; mpp.y+=mpv.y; We’ve simply resolved all the necessary references at the start of the calculation as local variables. This makes the code more readable and, more important, reduces the work that the interpreter needs to do. Listing 8.7 shows the code for the complete web page that allows the two algorithms to be profiled side by side. Listing 8.7 Profiling variable resolution
-->