Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift compilation time with nil coalescing operator

After reading of the article about swift compiling time. I am interested in why usage of more than 2 sequence coalescing operator increase compilation time significantly.

Example: Compilation time 3.65 sec.

 func fn() -> Int {    
        let a: Int? = nil
        let b: Int? = nil
        let c: Int? = nil

        return 999 + (a ?? 0) + (b ?? 0) + (c ?? 0)
 }

Compilation time 0.09 sec.

func fn() -> Int {

    let a: Int? = nil
    let b: Int? = nil
    let c: Int? = nil

    var res: Int = 999

    if let a = a {
        res += a
    }

    if let b = b {
        res += b
    }

    if let c = c {
        res += c
    }

    return res
}  
like image 891
Oleg Gordiichuk Avatar asked May 08 '16 12:05

Oleg Gordiichuk


People also ask

What is the nil coalescing operator in Swift?

Swift's nil coalescing operator helps you solve this problem by either unwrapping an optional if it has a value, or providing a default if the optional is empty. Because name is an optional string, we need to unwrap it safely to ensure it has a meaningful value.

What is nil coalescing & ternary operator?

The nil-coalescing and ternary conditional operators are what's known as syntatic sugar. They sugar-coat verbose code in more concise code, and make your Swift code more readable.


1 Answers

I'm almost certain that this has to do with type inference. When interpreting all of those + and ?? operators the compiler is doing a lot of work behind the scenes to infer the types of those arguments. There are around thirty overloads for the + operator alone and when you chain several of them together you are making the compiler's job much more complicated than you might think.

like image 123
Aaron Rasmussen Avatar answered Sep 23 '22 06:09

Aaron Rasmussen