Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
}
like image 627
Ted Avatar asked Nov 29 '25 17:11

Ted


1 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

like image 152
Patrick Avatar answered Dec 02 '25 07:12

Patrick