I have a cubic 3D array "class" like this:
function Array3D(size) {
this.data = new Array(size*size*size);
var makeIndex = function(p) {
return p[0] + p[1]*size + p[2]*size*size;
}
this.get = function(p) { return this.data[makeIndex(p)]; };
this.set = function(p, value) { this.data[makeIndex(p)] = value; };
}
I'd like to generalize to multiple dimensions, but without affecting access performance. Here's my simple approach:
function ArrayND(size, N) {
var s = 1;
for(var i = 0; i < N; i++) s *= size;
this.data = new Array(s);
var makeIndex = function(p) {
var ind = 0;
for(var i = N-1; i >= 0; i--)
ind = ind*size + p[i];
return ind;
}
this.get = function(p) { return this.data[makeIndex(p)]; };
this.set = function(p, value) { this.data[makeIndex(p)] = value; };
}
Is there any way I can "unroll" my makeIndex
function, so that the loop is evaluated once at declaration time, but not upon invokation? Would the overhead of using runtime-generated code from eval
or new Function()
cancel out the benefit of not looping?
Both size
and N
are essentially constants, so the repeated multiplication and iteration feels like something that could be done only once.