Skip to content

Instantly share code, notes, and snippets.

@ppeelen
Last active June 14, 2021 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ppeelen/2397d6a67667bce7f38dc1ee3b49f1c3 to your computer and use it in GitHub Desktop.
Save ppeelen/2397d6a67667bce7f38dc1ee3b49f1c3 to your computer and use it in GitHub Desktop.
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