Why does it take a long time to compile when a tuple of a struct is held by another struct?

Viewed 146

Environment

PC: MacBook Pro (13-inch, M1, 2020)
Xcode: Version 13.0

Details

For example, the following code takes about 3 seconds to build on average.

struct Foo {
    let num: Int = 0
}

struct Demo1 {
    let foos = (Foo(), Foo(), Foo(), Foo(), Foo(),
                Foo(), Foo(), Foo(), Foo(), Foo())
}

struct Demo2 {
    let foos = (Demo1(), Demo1(), Demo1(), Demo1(), Demo1(),
                Demo1(), Demo1(), Demo1(), Demo1(), Demo1())
}

struct Demo3 {
    let foos = (Demo2(), Demo2(), Demo2(), Demo2(), Demo2(),
                Demo2(), Demo2(), Demo2(), Demo2(), Demo2())
}

struct Demo4 {
    let foos = (Demo3(), Demo3(), Demo3(), Demo3(), Demo3(),
                Demo3(), Demo3(), Demo3(), Demo3(), Demo3())
}

On the other hand, if you replace struct with class, the average time is about 0.4 seconds.

struct Foo {
    let num: Int = 0
}

struct Demo1 {
    let foos = (Foo(), Foo(), Foo(), Foo(), Foo(),
                Foo(), Foo(), Foo(), Foo(), Foo())
}

class Demo2 {
    let foos = (Demo1(), Demo1(), Demo1(), Demo1(), Demo1(),
                Demo1(), Demo1(), Demo1(), Demo1(), Demo1())
}

class Demo3 {
    let foos = (Demo2(), Demo2(), Demo2(), Demo2(), Demo2(),
                Demo2(), Demo2(), Demo2(), Demo2(), Demo2())
}

class Demo4 {
    let foos = (Demo3(), Demo3(), Demo3(), Demo3(), Demo3(),
                Demo3(), Demo3(), Demo3(), Demo3(), Demo3())
}

Why does the difference between struct and class make a difference? I would appreciate any advice on the cause.

2 Answers

Because in the second case you have list of pointers (class objects) and in the first case list of structure, so the compiler will have to compute the total structures contained in each structure. With structs the final object is large, with classes the final object is much much smaller.

Don't rely on implicit typing. That just yanks the compiler's chain. You know the type of each variable so declare that type and watch compile times get much shorter!

Related