HTML and CSS Reference
In-Depth Information
Listing 4-2. A Flat Particle Structure
position_x: <number>
position_y: <number>
position_z: <number>
velocity_x: <number>
velocity_y: <number>
velocity_z: <number>
The code in Listing 4-2 is clearly very simplified, but illustrates an effective way of reducing the object count
(and thereby memory usage) and the number of property lookups required to access various properties (improving
A simple particle simulation based on these structures (particles accelerating under gravity) shows that
flattening the structure in this way yields a memory saving of between 25% and 35%, and execution of a trivial particle
simulation (updating position based on velocity, and velocity based on a fixed acceleration vector) showed a speed
increase of roughly 25% on all browsers, with one browser showing roughly a 30% reduction in execution cost.
We can explain the memory savings by noting that each particle is now represented as a single Object with a list
of six properties, rather than three Objects: particle, position, and velocity with a combined property count of eight
and, more significantly, all of the extra properties and infrastructure required by the JavaScript runtime. Execution
cost savings likely result because fewer property lookup and dereferencing operations are required to reach a given
piece of data.
As a storage mechanism, JavaScript Arrays can often be more efficient than Objects in several scenarios. Most
JavaScript engines have optimized implementations of Arrays, with very low overhead for access to indexed
properties, efficient storage of sparse data, and flags to inform that garbage collector when the Array does not need to
be traversed (e.g. if it only contains primitive data such as numbers).
The process of looking up indexed properties on Arrays is generally cheaper than accessing named properties
on generic Objects. This is particularly true when the indices or keys are fully dynamic (and thereby the JIT compiler
cannot predict them at compile time), as well as for code that iterates through all items in a structure.
Structures such as those discussed in the simple particle example in Listing 4-1 are very commonly stored in
Arrays (a so-called “array of structures”). In this case, a very effective way to save memory is to completely flatten an
array of Particle structures into a “structure of arrays,” as shown in Listing 4-3.
Listing 4-3. A List of Particles as a Structure of Arrays
// Each particle consists of 6 numbers
var particles_posx = new Array(numParticles);
var particles_posy = new Array(numParticles);
var particles_posz = new Array(numParticles);
var particles_velx = new Array(numParticles);
var particles_vely = new Array(numParticles);
var particles_velz = new Array(numParticles);
In this way, code accesses and uses the data as shown in Listing 4-4.
Search WWH ::

Custom Search