.map VS for loop Performance Test in Swift 3 | iOS

I was very curious to see how map performed against a traditional way for loop so I decided to run a sample code. One class with two different methods operating the same thing one using for loop and another using map.

import Foundation

//Random Array
var array = [Int].init(repeating: 1, count:3000)

//Operation class
class Operation {

    static func testForIn() -> [Int] {
        var newArr : [Int] = []
        for value in array {
            newArr.append(value * 2)
        }
        return newArr
    }

    static func testInMap() -> [Int] {
        return array.map({ (value) in
            value * 2
        })
    }
}

let start1 = Date()
Operation.testForIn()
let start2 = Date()
Operation.testInMap()
let start3 = Date()

print(start2.timeIntervalSince(start1))
print(start3.timeIntervalSince(start2))

And response we really amazing.
For loop case it takes

14.6862210035324

And for .map it takes

0.122562050819397

Thank you for reading this, pleaes do share and comment if you have anything.

One thought on “.map VS for loop Performance Test in Swift 3 | iOS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s