Search code examples
javascriptperformancearraybuffertyped-arrays

JavaScript typed arrays for all variables?


I am writing some code for a research project. I am writing it in javascript because I want to be able to run it anywhere and to be able to publish it on the web when I finish the project. But I also need to rerun this code hundreds of thousands of times and look at the results as part of the research project so I want it to be efficient. For the webgl part of the project I am using an array buffer and typed arrays.

Would using an array buffer or typed array for all the javascript variables give normal javascript any performance improvements?


From what I have read it sounds like this is what web assembly and some transpilers are doing.


Solution

  • It is definitely possible to take advantage of some of the same typed array techniques that give web-assembly their boost. However as can be seen in the code snippet, naively replacing JS standard array with a typed array does not affect performance in any major way on e.g Chrome. (In fact, in the example the observed effect was negative)

    let a = [];
    let A = new Float64Array(1000000)
    let b = [0, 0, 0, 0, 0, 0, 0, 0];
    let B = new Float64Array(8);
    for (let i = 0; i < 1000000; i++) {
      let v = Math.sqrt(1+i)
      a[i] = v;
      A[i] = v;
    }
    
    
    tn = performance.now()
    for (let n = 0; n < 500; n++) {
      for (let i = 0; i < 999999; i++) {
        B[i % 8] = B[i % 8] + (A[i] * A[i])
      }
    }
    let SUM = 0;
    for (let i = 0; i < 8; i++) {
      SUM = SUM + B[i];
    }
    console.log("   TYPED ARRAY", performance.now() - tn, SUM)
    
    
    tn = performance.now()
    for (let n = 0; n < 500; n++) {
      for (let i = 0; i < 999999; i++) {
        b[i % 8] = b[i % 8] + (a[i] * a[i])
      }
    }
    let sum = 0;
    for (let i = 0; i < 8; i++) {
      sum = sum + b[i];
    }
    console.log("standard array", performance.now() - tn, sum)