Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array map vs. forEach in Swift

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?

like image 596
CommaToast Avatar asked Aug 02 '17 01:08

CommaToast


People also ask

What is the difference between array map and array forEach?

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.

Is map faster than for loop Swift?

The built-in flatMap function is a little bit slower than the for-in loop. Custom for-in loop flatMap is 1.06x faster.

What is the difference between map () and forEach ()?

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.”

Is map more efficient than forEach?

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.


1 Answers

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.

forEach vs Map performance test

like image 91
adev Avatar answered Sep 25 '22 02:09

adev