Improve the speed of a JavaScript function Improve the speed of a JavaScript function arrays arrays

Improve the speed of a JavaScript function


For this kind of array maipulations, you better not use build in methods, like slice or reduce, because they are slow in comparison to a for loop, or any other looping approaches.

This approach takes a sinlge loop and uses the index for getting a value of the given array and takes the last sum of the new array.

Some speed tests on Codewars: Sums of Parts:

  • 5621 ms with sparse array sum = []; sum[i] = 0; (the first version of this answer),
  • 3452 ms with Array(i + 1).fill(0) and without sum[i] = 0;,
  • 1261 ms with Array(i + 1) and sum[i] = 0; (find below),
  • 3733 ms with Icepickle's first attempt.

const    partsSums = (ls) => {        let i = ls.length;        const sum = Array(i + 1);        sum[i] = 0;        while (i--) sum[i] = sum[i + 1] + ls[i];        return sum;    },    ls = [0, 1, 3, 6, 10];console.log(...partsSums(ls));