Given the following data structs:
struct Base {
let nested1: Nested1
let nested2: Nested2
}
struct Nested1 {
let grand1: GrandChild
let grand2: GrandChild
}
struct Nested2 {
let grand: GrandChild
}
struct GrandChild { }
I wrote two files to test compiler performance using hyperfine (thanks @Jon_Shier ):
hyperfine 'xcrun swiftc -typecheck FILENAMEGOESHERE' --show-output --warmup 1
One file contained the following, using typed init:
let base0 = Base(nested1: Nested1(grand1: GrandChild(), grand2: GrandChild()), nested2: Nested2(grand: GrandChild()))
...
let base999 = Base(nested1: Nested1(grand1: GrandChild(), grand2: GrandChild()), nested2: Nested2(grand: GrandChild()))
The other one contained the same structure, initialized using bare inits:
let base0: Base = .init(nested1: .init(grand1: .init(), grand2: .init()), nested2: .init(grand: .init()))
...
let base999 = .init(nested1: .init(grand1: .init(), grand2: .init()), nested2: .init(grand: .init()))
However the .init version was faster, consistently. Tried it across different versions of Xcode, but it was slower for every version, more than double in 15.2.
Test | 13.0 | 14.0.1 | 14.2 | 15.1 | 15.2 |
---|---|---|---|---|---|
Bare Init | 616.7 | 675.4 | 715.9 | 1219.0 | 1204.0 |
Typed Init | 801.1 | 823.8 | 872.8 | 2836.0 | 2772.0 |
I don't really understand why .init would be faster, as the type has to be deduced. In other tests, for example complex nested dictionaries typing the dict types at its declaration would make it much faster.
I had situations where nested .init was really, really slow for some reason (tripping up the 1s limit) where it had to be fixed by typing everything. I was trying to recreate that, but I'm seeing the inverse here.