Is there some way to figure out why different writing in Swift cause so huge gap of compile time?

Viewed 58

There are two different writing:

func dicFuncA() -> Dictionary<String, Any> {
    return [
        "a": "ooo",
        "b": 30,
        "c": [1, 2, 3],
        "d": 2.33
    ]
}

And

func dicFuncB() -> Dictionary<String, Any> {
    let dic: [String : Any] = [
        "a": "ooo",
        "b": 30,
        "c": [1, 2, 3],
        "d": 2.33
    ]

    return dic
}

When add "-Xfrontend -debug-time-function-bodies" to Other Swift Flags:

enter image description here

We can get the compile time of the function:

enter image description here

The compile time of dicFuncA is about 54 times longer than the time of dicFuncB!

That's Why?

Probably, it's the cause of type check. But, is there some way to figure out what the compiler have done during the compile time?

I try to use swiftc command, like -dump-ast/-dump-parse, to find out the real reason. But, still confused.

1 Answers

That's a good observation you have made. In Swift when the datatype is not defined the compiler must infer it. Let's see what Apple Documentation says about it:

...the type information is passed up from the leaves of the expression tree to its root. That is, the type of x in var x: Int = 0 is inferred by first checking the type of 0 and then passing this type information up to the root (the variable x).

So the compiler must check the type of each tuple in the dictionary and accordingly set the type of the dictionary. This operation is expensive.

Just for fun you can see how compile time correlates to the number of tuples.

Related