Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mateuszszklarek/59fafc8159c6868c6d64e8fd61cbf0e1 to your computer and use it in GitHub Desktop.
Save mateuszszklarek/59fafc8159c6868c6d64e8fd61cbf0e1 to your computer and use it in GitHub Desktop.
#!/usr/bin/swift
import Foundation
func measure(_ title: String, operation: () -> Void) {
let closedRange = 0...4
let averageTimeInSeconds = closedRange
.map { _ -> CFAbsoluteTime in
let startTime = CFAbsoluteTimeGetCurrent()
operation()
return CFAbsoluteTimeGetCurrent() - startTime
}
.reduce(0.0, +) / Double(closedRange.count)
print("Average time from 5 executions: `\(title)` => \(averageTimeInSeconds)s.")
}
let a = "I'm"
let b = "iOS"
let c = "Developer"
measure("string interpolation") {
for _ in 0...99_999 {
let _ = "\(a) an \(b) \(c)"
}
}
measure("string concatenation") {
for _ in 0...99_999 {
let _ = a + " an " + b + " " + c
}
}
measure("string concatenation using joined(separator:) function") {
for _ in 0...99_999 {
let _ = [a, b, "an", c].joined(separator: " ")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment