array-smooth
array-smooth copied to clipboard
Inefficient algorithm
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.
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 🙂
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
Cool! I will take a look at the jsperf! Thanks @murrayju