HTML and CSS Reference
In-Depth Information
Listing 4-4. Simulation Code Using a Structure of Arrays
var velocity_x;
var velocity_y;
var velocity_z;
for (var i = 0 ; i < numParticles; ++i)
{
velocity_x = particles_velx[i];
velocity_y = particles_vely[i];
velocity_z = particles_velz[i];
particles_posx[i] += deltaTime * velocity_x;
particles_posy[i] += deltaTime * velocity_y;
particles_posz[i] += deltaTime * velocity_z;
// continue simulation ...
}
In Listing 4-4, all data is stored in just six Objects. Compared to the Array of flattened Objects, some simple
experiments showed this to yield a memory savings of between 35% and 45%. That is a 40% to 60% savings compared
to the original hierarchical version. This memory savings is a result of drastically reducing the number of Objects
required to maintain the data, and allowing the JavaScript engine to store it as a few large contiguous lists of values
rather than a large list of references to structures, each with some named properties.
Note that although the way the data is referenced has changed, the impact on the maintainability of the code is
small. The effort required to add or remove properties from individual particles is roughly the same as it would be for
the original data structure.
You can reduce object count even further if you are willing to sacrifice some readability (see Listing 4-5).
Listing 4-5. A Single Interleaved Array
// Each particle consists of 6 numbers
// Single Array containing the all particle attributes.
// [ posx, posy, posz, velz, vely, velz, // particle 0
// posx, posy, posz, velz, vely, velz, // particle 1
// posx, posy, posz, velz, vely, velz, // particle 2
// . . .
// ]
var particles = new Array(6 * numParticles);
The code in Listing 4-5 maintains a single Array containing all properties of all objects. Individual properties of a
given particle must be addressed by their relative indices, as shown in Listing 4-6.
Listing 4-6. Simulation Code Using a Single Interleaved Array
var velocity_x;
var velocity_y;
var velocity_z;
var endIdx = 6 * numParticles;
for (var i = 0 ; i < endIdx ; i = i + 6)
 
Search WWH ::




Custom Search