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 n
- 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;
- Set a member of an existing array to
var arr = [1,2,3]; arr = 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:
undefined members of an array. Iteration based on length, like typical
while loops, work fine. But
.map work like for-in which skips the
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.