Skip to content

Instantly share code, notes, and snippets.

@stevekane
Created October 10, 2014 21:54
Show Gist options
  • Save stevekane/75cc7aa71a833fbde4e7 to your computer and use it in GitHub Desktop.
Save stevekane/75cc7aa71a833fbde4e7 to your computer and use it in GitHub Desktop.
An example of avoiding double allocation when building typed arrays by iterating twice
/*
When creating typed arrays (Float32Array etc) in javascript you often need
to first create a plan Array and then pass it to the typed array constructor
to get out the final memory-packed typed array.
In a tight gameloop, these arrays can be very large and allocating the
javascript array is undesireable as it puts additional GC pressure on your
app which has memory implications and also may produce jutter on devices that
interupt the main javascript thread to do GC.
In many, many apps, iteration and in general CPU use is not even close to
the bottleneck. As such, avoiding unneeded allocations is a stronger engineering
goal than avoiding CPU work.
In the two code sample below, I firstly showcase the typical method of allocating both
the plain Array and then the Typed Array. I secondly show the same function
implemented with double the iteration but only a single typed array allocation.
*/
//here we allocate both the JS array and Float32Array
function buildPositions (particles) {
var out = []
for (var i = 0; i < particles.length; ++i) {
if (particles[i].living) {
out.push(particles[i].position[0])
out.push(particles[i].position[1])
out.push(particles[i].position[2])
}
}
return new Float32Array(out)
}
//here we allocate once and iterate twice
function buildPositions (particles) {
var livingCount = 0
var out
for (var i = 0; i < particles.length; ++i) {
if (particles[i].living) livingCount++
}
out = new Float32Array(livingCount * 3)
for (var j = 0, index = 0; j < particles.length; ++j) {
if (particles[j].living) {
out.set(particles[j].position, index)
index += 3
}
}
return out
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment