Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: 10 x speedup via loop inline?

I'm running into a performance problem with a strange behaviour of javascript inside my Firefox (13.0.1). The newest Chrome shows the same behaviour.

When I execute my javascript code which looks like the code snippet below, the result is pretty slow. However, I get about 10 x speedup if I simply inline the content of the outer loop over 'j'. For my example application, this means that I'm simply writing it two times for fixed values of 'j=0' and 'j=1' respectively, as 'm' equals 2. Of course, I don't want 'm' to be hard-coded, so I'm asking myself what exactly causes this slowdown when using a real loop?

Does anybody have an idea?

I'm running the code inside a web worker. Weird enough, the positive effect of the inlining does not occur if I execute the same in the main javascript context, instead of the worker's context. Nevertheless, executing the loop content only for one value of 'j' brings the huge speedup helps in all cases. Could this also have something to do with memory management?

Thanks a lot in advance!

//m: very small, 1-2
for (j = 0; j < m; ++j) {
  var attrib = attributes[j];

  //n: very large, ~3*10^6 elements
  for (i = 0; i < n; ++i) {

    var data = largeBuffer[i];

    //nc: very small, 2-3
    for (c = 0; c < nc; ++c) {
      var component;
      //compute 'component
      //..
      attrib.typedArray[baseIdx + c] |= component;
    }

    baseIdx += nc;
  }
}
like image 897
volzotan Avatar asked Jul 16 '12 11:07

volzotan


1 Answers

This is just an hypothesis. I do not know well the internals of JS interpreters.

Maybe when you inline the outer loop, the interpreter sees 4 times the same code and thus triggers the JIT. To the opposite, when you use a regular loop, the code is only seen once by the JIT.

Once again, this is only an hypothesis.

like image 89
yadutaf Avatar answered Nov 16 '22 19:11

yadutaf