array-smooth icon indicating copy to clipboard operation
array-smooth copied to clipboard

Inefficient algorithm

Open murrayju opened this issue 6 years ago • 3 comments

This algorithm has a worst case runtime of at least N^3, and an average of at least N^2. There are linear solutions for a moving average, so this stands to be improved drastically. In its current form, this would be unusable on large datasets, especially where performance is a concern.

While the functional style methods of Array.prototype are convenient, nesting them in this way is wildly inefficient. You should look into immutable.js sequences to chain operations efficiently, if you want to continue to use that style.

murrayju avatar Jul 02 '18 15:07 murrayju

Yeah I took a naive approach considering a large data set. My use case was not that large. Thanks for taking the time to review and comment, I will improve it when I have a bit of time 🙂

ndelvalle avatar Jul 03 '18 02:07 ndelvalle

The new implementation is still O(N^2) (nested for loops). It is possible to implement this as O(N), using a single for loop. Use a variable to hold the running sum. In each loop iteration, add the next value to the sum and subtract the value exiting the window (if applicable).

I wrote up some comparisons on jsperf: https://jsperf.com/moving-average-algorithms/1

murrayju avatar Jul 11 '18 14:07 murrayju

Cool! I will take a look at the jsperf! Thanks @murrayju

ndelvalle avatar Jul 29 '18 22:07 ndelvalle