Skip to content

Instantly share code, notes, and snippets.

@toshi0383 toshi0383/map.swift
Created Oct 2, 2015

Embed
What would you like to do?
import Foundation
extension Array {
func map7<U>(@noescape transform: Element ->U) -> [U] {
var result = UnsafeMutablePointer<U>.alloc(1000)
let resultBuffer = UnsafeMutableBufferPointer(start: result, count: 1000)
self.withUnsafeBufferPointer { (buffer:UnsafeBufferPointer<Element>) in
for element in buffer {
result.memory = transform(element)
result = result.successor()
}
}
return [U](resultBuffer)
}
}
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 b1 = a.map{$0 + 1}
measure("map ")
let h1 = a.map7{$0 + 1}
measure("map7")
let b2 = a.map{$0 + 1}
measure("map ")
let h2 = a.map7{$0 + 1}
measure("map7")
let b3 = a.map{$0 + 1}
measure("map ")
let h3 = a.map7{$0 + 1}
measure("map7")
let b4 = a.map{$0 + 1}
measure("map ")
let h4 = a.map7{$0 + 1}
measure("map7")
// $ xcrun -sdk macosx swiftc map.swift # CoreGraphicsがimportできないからこうしろとおこられた
// $ ./map
// === : 0.000325918197631836
// map : 0.000761985778808594
// map : 0.000236988067626953
// map7: 0.000210046768188477
// map : 0.000227928161621094
// map7: 0.00017094612121582
// map : 0.000341176986694336
// map7: 0.000142812728881836
// map : 0.000211954116821289
// map7: 0.000133037567138672
// $ xcrun -sdk macosx swiftc -O map.swift
// $ ./map
// === : 0.000318050384521484
// map : 0.000821113586425781
// map : 5.79357147216797e-05
// map7: 3.00407409667969e-05
// map : 5.10215759277344e-05
// map7: 2.88486480712891e-05
// map : 5.10215759277344e-05
// map7: 2.62260437011719e-05
// map : 4.98294830322266e-05
// map7: 2.59876251220703e-05
// 0255a1c9c760eb7da52a $
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.