Memory usage when using Array iterative methods? #7916
-
|
I'd like some wisdom on when/how to use use Array iterative methods. For example: Is the In Python, this kind of thing would involve iterators, and no intermediate Back to the concrete example, would it be better (always? sometimes?) to skip the chained methods and rewrite it as: And, just to help me understand JS better in general: would ES6+ JS be any different from Espruino in this regard? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
As you suggest, for each function call you actually end up with a new array being allocated. In theory with ES6 iterators you could avoid this, but they're not implemented in Espruino at the moment. In your example, map->filter->forEach, yes, it'd be faster/more efficient to just combine the code into one function unless you had a specific reason not to (like code re-use). A lot of it really depends on the size of your array though. If you've got 100 elements in the array it doesn't really matter if you temporarily allocate a new one and it's more about readability. If you've got thousands of items you're going to have to be very careful with memory use anyway, and you probably want to be thinking about using Typed Arrays if it's possible. |
Beta Was this translation helpful? Give feedback.
As you suggest, for each function call you actually end up with a new array being allocated.
In theory with ES6 iterators you could avoid this, but they're not implemented in Espruino at the moment.
In your example, map->filter->forEach, yes, it'd be faster/more efficient to just combine the code into one function unless you had a specific reason not to (like code re-use).
A lot of it really depends on the size of your array though. If you've got 100 elements in the array it doesn't really matter if you temporarily allocate a new one and it's more about r…