M
M
Maxim Ko2020-10-22 08:31:05
JavaScript
Maxim Ko, 2020-10-22 08:31:05

How to improve the performance of js code?

Good day, Khabrovites!
Recently I started to study on codewars and there was 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 the global test, it runs for more than 12 seconds. How can I reduce code execution time? What optimization techniques should be applied here?
https://www.codewars.com/kata/5ce399e0047a45001c85... - link to kata

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
RAX7, 2020-10-22
@MisticX

there was a problem with the speed of code execution

The problem is in the algorithm itself. It is not necessary to sum the elements of the array on each nested iteration, one pass through the array is enough. The code will have to be completely rewritten.
decision

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;
}

X
xmoonlight, 2020-10-22
@xmoonlight

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
PS link :
RAX7 , ... and mine is ~3000ms ¯\_(ツ)_/¯
can you squeeze even harder?)
PS2: RAX7 By the way, the best result there is also a mutation, but it works in 927.29ms (ours are 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);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question