Skip to content

Instantly share code, notes, and snippets.

@ppeelen
Last active June 14, 2021 10:14
Embed
What would you like to do?
An example on why not to try to reinvent the wheel, use the power of Swift.
import Foundation
enum FooBar: String, CaseIterable {
case Foo
case Bar
}
enum BarFoo: CaseIterable {
case Bar
case Foo
var name: String {
switch self {
case .Bar:
return "Bar"
case .Foo:
return "Foo"
}
}
}
let firstList = (0..<10000).compactMap { _ in FooBar.allCases.randomElement() }
let secondList = (0..<10000).compactMap { _ in BarFoo.allCases.randomElement() }
let firstStart = CFAbsoluteTimeGetCurrent()
firstList.forEach { item in
let foo = item.rawValue // Just to access the naming
}
let firstDiff = CFAbsoluteTimeGetCurrent() - firstStart
print("Using RawRepresentable took \(firstDiff) seconds")
let secondStart = CFAbsoluteTimeGetCurrent()
secondList.forEach { item in
let bar = item.name // Just to access the naming
}
let secondDiff = CFAbsoluteTimeGetCurrent() - secondStart
print("Using name var took \(secondDiff) seconds")
let comparison = secondDiff - firstDiff
let speed = secondDiff / firstDiff
print("Using RawRepresentable was \(comparison)s faster. In other words \(speed) faster.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment