In Swift arrays you can do:
var myArray = [1,2,3,4]
myArray.forEach() { print($0 * 2) }
myArray.map() { print($0 * 2) }
They both do the same thing. The only difference is .map also returns an array of voids as well, [(),(),(),()]
, which gets unused. Does that mean .map performs worse than .forEach when it's not assigning to anything?
Differences between forEach() and map() methods:The forEach() method does not create a new array based on the given array. The map() method creates an entirely new array. The forEach() method returns “undefined“. The map() method returns the newly created array according to the provided callback function.
The built-in flatMap function is a little bit slower than the for-in loop. Custom for-in loop flatMap is 1.06x faster.
forEach “executes a provided function once per array element.” Array. map “creates a new array with the results of calling a provided function on every element in this array.”
You can use both map() and forEach() interchangeably. The biggest difference is that forEach() allows the mutation of the original array, while map() returns a new array of the same size. map() is also faster.
In Swift as per Apple's definition,
map
is used for returning an array containing the results of mapping the given closure over the sequence’s elements
whereas,
forEach
calls the given closure on each element in the sequence in the same order as a for-in loop.
Both got two different purposes in Swift. Even though in your example map
works fine, it doesn't mean that you should be using map
in this case.
map
eg:-
let values = [1.0, 2.0, 3.0, 4.0]
let squares = values.map {$0 * $0}
[1.0, 4.0, 9.0, 16.0] //squares has this array now, use it somewhere
forEach
eg:-
let values = [1.0, 2.0, 3.0, 4.0]
values.forEach() { print($0 * 2) }
prints below numbers. There are no arrays returned this time.
2.0
4.0
6.0
8.0
In short to answer your questions, yes the array generated from map
is wasted and hence forEach
is what you should use in this case.
Update:
OP has commented that when he tested, the performance was better for map
compared to forEach
. Here is what I tried in a playground and found. For me forEach
performed better than map
as shown in image. forEach
took 51.31 seconds where as map
took 51.59 seconds which is 0.28 seconds difference. I don't claim that forEach
is better based on this, but both has similar performance attributes and which one to use, depends on the particular use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With