How to improve the performance of js code?

  • 0
    Good day, Khabrovites!
    I recently started working on codewars and had a problem with the speed of code execution.
    There is a code:
    function partsSums(ls) {
      ls.reverse();
      let a = 0;
      arr = [];
      let s = ls.length;
      for(let i = s; i--;){
        for(let j = ls.length; j--;){
          a += ls[j];
        }
        arr.push(a);
        ls.pop();
        a = 0;
      }
      arr.push(0);
      return ls ? arr : [0];
    }

    With a global test, it takes more than 12 seconds to run. How can I reduce my code execution time? What optimization techniques should be applied here?
    https: //www.codewars.com/kata/5ce399e0047a45001c85 ... - link to katu
    JavaScript Anonymous, Apr 28, 2019

  • 2 Answers
  • 0
    there was a problem with the speed of code execution


    The problem is in the algorithm itself. There is no need to sum the array elements at each nested iteration, just one pass through the array is enough. The code will have to be completely rewritten.

    solution


    function partsSums(ls) {
    const result = new Array(ls.length + 1);
    result[ls.length] = 0;

    for (let i = ls.length - 1; i > -1; i--) {
    result[i] = result[i + 1] + ls[i];
    }

    return result;
    }

    Anonymous

  • 0
    I did it like this:

    function partsSums(ls) {
    if(ls.length==0) return [0];
    result=ls;
    result[i=result.length]=0;
    i--;
    while(i!==-1)
    result[i] = result[i+1]+ls[i--];
    return result;
    }
    Test Results:

    partsSums

    Basic tests

    Random tests

    Completed in 2070ms
    link



    PS:
    RAX7 , ... and mine in ~ 3000ms ¯ \ _ (ツ) _ / ¯
    will you squeeze it even cooler?)



    PS2: RAX7 BTW, there is the best result - this is also a mutation, but it works in 927.29ms (ours - less than 100ms).

    function partsSums(ls) {
    ls.unshift(0);
    let sum = ls.reduce((p, c) => p + c, 0);
    return ls.map(v => sum = sum - v);
    }
    Sebastian O'Neill

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!