3 ms·
While your example reads a bit better, you’re now iterating through your list twice.
by mikeryan 7y ago
While your example reads a bit better, you’re now iterating through your list twice.
- fwip 7y agoMost code isn't performance-critical. This pattern will probably be dominated by the time taken to filter and map, not loop iteration.
- londt8 7y agoTechnically there is no iteration in filter/map/reduce at all.
- Stratoscope 7y agoThat's incorrect. All of those functions are implemented using iteration. Consider this excerpt from the .map() polyfill on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map#Polyfill https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... // 7. Let k be 0 k = 0; // 8. Repeat, while k < len while (k < len) { // [loop body omitted] // d. Increase k by 1. k++; }
- saagarjha 7y agoDoes JavaScript have adapters to covert lists into generators or lazy iterators?
- hn_throwaway_99 7y agoUnfortunately not in a way that can optimize these methods. This is one reason the Java Streams API, which has a similar purpose (e.g. map, filter, flatMap, reduce, etc.), is a better design IMO because you can chain together method calls without creating (and iterating) the full array at each step.