Is there performance/compiler benefits when using tuple vs struct whenever possible?

Viewed 272

Is there performance/compiler benefits when using tuple vs struct whenever possible?

For example in this case where

  • you don't need protocol conformance,
  • you don't need functions,
  • all variables are readonly.

.

typealias SomeModel = (
    name: String,
    id: String
)

vs

struct SomeModel {
    let name: String
    let id: String
}
2 Answers

I don't have a formal answer to your question but here is a very basic test comparing creation times.

import Foundation

func duration(_ block: () -> ()) -> TimeInterval {
    let start = CFAbsoluteTimeGetCurrent()
    block()
    let end = CFAbsoluteTimeGetCurrent()
    return end - start
}

struct Person {
    let first: String
    let last: String
}

let total = 99999
let structTest = duration {
    for _ in (0...total) {
        let person = Person(first: "", last: "")
    }
}
let tupleTest = duration {
    for _ in (0...total) {
        let person = (first: "", last: "")
    }
}

print(structTest, tupleTest)

The results were: 1.3234739303588867 1.1551849842071533

Create following function to calculate a time for operations. Put blocks of your code as its argument and try to see a difference by yourself:

func duration(_ block: () -> ()) -> TimeInterval {
  let startTime = Date()
  block()
  return Date().timeIntervalSince(startTime)
}
Related