what is the best way to scroll through a list of _.map and _.forEach in lodash? I do not need the return value but I only do something inside the loop.
In terms of performance, which is the difference between the two functions?
a = []
b = []
list = response._source.carico_scarico
if angular.isDefined(list)
_.forEach(list, (cs) ->
if cs.qta >= 0 then a.push cs
if cs.qta < 0 then b.push cs
)
Or
a = []
b = []
list = response._source.carico_scarico
if angular.isDefined(list)
_.map(list, (cs) ->
if cs.qta >= 0 then a.push cs
if cs.qta < 0 then b.push cs
)
what is the best way to scroll through a list of _.map and _.forEach in lodash? I do not need the return value but I only do something inside the loop.
In terms of performance, which is the difference between the two functions?
a = []
b = []
list = response._source.carico_scarico
if angular.isDefined(list)
_.forEach(list, (cs) ->
if cs.qta >= 0 then a.push cs
if cs.qta < 0 then b.push cs
)
Or
a = []
b = []
list = response._source.carico_scarico
if angular.isDefined(list)
_.map(list, (cs) ->
if cs.qta >= 0 then a.push cs
if cs.qta < 0 then b.push cs
)
Share
Improve this question
edited Apr 27, 2015 at 12:54
T.J. Crowder
1.1m200 gold badges2k silver badges2k bronze badges
asked Apr 27, 2015 at 12:46
YoBreYoBre
2,5305 gold badges28 silver badges37 bronze badges
4
- 3 you should do your own performance calculations. – Daniel A. White Commented Apr 27, 2015 at 12:48
- 1 "In terms of performance" - you need to objectively measure this yourself – James Thorpe Commented Apr 27, 2015 at 12:48
- So there is no way to know absolutely if one method is better than the other? – YoBre Commented Apr 27, 2015 at 12:58
- 2 There's a way to know absolutely for a given use case: Measure it. – T.J. Crowder Commented Apr 27, 2015 at 12:59
1 Answer
Reset to default 8In terms of performance, which is the difference between the two functions?
It's extremely unlikely to matter. If you're worried about it mattering, create a test that's representative of your real code and try it (perhaps on http://jsperf.). But unless you're dealing with hundreds of thousands of entries, or repeating your loop hundreds of thousands of times, the real-world impact of any difference between them is likely to be nothing. (Heck, with modern JavaScript engines, hundreds of thousands may not even be enough to see a difference you'd care about.)
But speculating: As map
has to create and populate an array to use as a return value (which you're going to ignore), and forEach
doesn't, it stands to reason that map
will be very very slightly slower.
But: The bigger argument here is using the right tool for the job: If you don't need the return value, don't use map
. Its purpose is to create a result by mapping values from the original object into a new one. You don't want that, so map
is an odd choice, likely to trip up people doing maintenance on the code down-the-line.