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