Sparse Arrays For String Building
A sparse array is an instance of Array
that has undefined
as one or more members. I’ve seen them used, for
performance reasons, in game engines to pre-allocate a buffer. I believe it has something to do with one versus two
operations–altering a member versus adding a member and increasing length. But there are other uses for them if you
know what you can and can’t do with them.
Ways to create sparse arrays:
Array(n)
where n is an integer, will create an array with nundefined
members- Alter the length property of an existing array (with fewer members than the new length):
var arr = []; arr.length = 1;
- Delete a member from an existing array, or by deleting a member.
var arr = [1,2,3]; delete arr[1];
- Set a member of an existing array to
undefined
.var arr = [1,2,3]; arr[1] = void(0);
- Create an array literal with commas and no value:
var arr = [,,,];
A co-worker was trying to make a repeating string and used a sparse array; it looked something like this:
Both statements fail for the same reason: the JavaScript engine does not iterate over undefined
members of an array. Iteration based on length, like typical for
and while
loops, work fine. But .forEach
and .map
work like for-in which skips the undefined
member(s).
I came up with some variations of this idea that work (seen here: jsPerf). The test task was to write code that will inject a “test” td at the fourth position of 9 (otherwise empty) td’s. Some are quite nice syntactically, but none seem to perform like a for
loop. This one was my favorite for its simplicity.