Skip to content

Instantly share code, notes, and snippets.

@toshi0383
Last active January 10, 2021 08:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toshi0383/0255a1c9c760eb7da52a to your computer and use it in GitHub Desktop.
Save toshi0383/0255a1c9c760eb7da52a to your computer and use it in GitHub Desktop.
Custom map implementation performance test in Swift
import Foundation
// used in map5
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
let group = dispatch_group_create()
extension Array {
func map2<U>(transform: Element ->U) -> [U] {
return reduce([]) {
$0 + [transform($1)]
}
}
func map3<U>(transform: Element ->U) -> [U] {
var result = [U]()
for e in self {
result.append(transform(e))
}
return result
}
func map4<U>(transform: Element ->U) -> [U] {
var result = [U](count: self.count, repeatedValue: transform(self[0]))
for (idx,item) in enumerate() {
result.withUnsafeMutableBufferPointer{(inout p:UnsafeMutableBufferPointer<U>) in
p[idx] = transform(item)
}
}
return result
}
/// @see http://blog.scottlogic.com/2014/10/29/concurrent-functional-swift.html
func map5<U>(transform: Element ->U, callback:[U]->()) {
var result = [U](count: self.count, repeatedValue: transform(self[0]))
for (idx,item) in enumerate() {
result.withUnsafeMutableBufferPointer{(inout p:UnsafeMutableBufferPointer<U>) in
dispatch_group_async(group, queue) {
p[idx] = transform(item)
}
}
}
dispatch_group_notify(group, queue) {
callback(result)
}
}
}
var time = NSDate().timeIntervalSince1970
func measure(message: String? = nil) -> Double {
let now = NSDate().timeIntervalSince1970
let diff = now - time
if let message = message {
print("\(message): \(diff)")
}
time = now
return diff
}
let a:[Int] = (1...1000).map{$0}
measure()
let b = a.map{$0 + 1}
measure("map ")
let c = a.map2{$0 + 1}
measure("map2")
let d = a.map3{$0 + 1}
measure("map3")
let e = a.map4{$0 + 1}
measure("map4")
var f:[Int] = []
measure()
a.map5({$0 + 1}, callback: {f = $0;measure("map5")})
// $ swift map.swift
// map : 0.000206947326660156
// map2: 0.00310802459716797
// map3: 0.000529050827026367
// map4: 0.00117397308349609
// map5: 0.00284814834594727
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment