Skip to content

[SR-1577] Ternary operator much slower to compile than if / else #44186

Closed

Description

@josephlord
Previous ID SR-1577
Radar None
Original Reporter @josephlord
Type Improvement
Additional Detail from JIRA
Votes 2
Component/s Compiler
Labels Improvement, Performance, TypeChecker
Assignee None
Priority Medium

md5: ff256899ba0f3da0f98368b68df0de47

Issue Description:

A function with this line took about 4 seconds to compile in debug.

let sorted = picks.sort { $0.pick_line == $1.pick_line ? $0.position < $1.position : $0.pick_line < $1.pick_line }

This equivalent version took only 5.4ms:

    let sorted = picks.sort {
        if $0.pick_line == $1.pick_line {
            return $0.position < $1.position
        } else {
            return $0.pick_line < $1.pick_line
        }
    }

picks is an array of instances of an NSManagedObject subclass, position and pick_line are both optional Integer types. (I don't know if this is relevant).

Not sure if this should be labelled "Performance". Is that for issues in the compilation time or the performance of the compiled code.

Activity

  1. belkadan commented on May 21, 2016

    @belkadan
    Contributor

    The label's context-sensitive. Maybe we should have CompilerPerf and RunTimePerf instead.

  2. belkadan commented on May 21, 2016

    @belkadan
    Contributor

    There are several factors that would make the first one slower, the main one being that everything's type-checked together. Specifically:

    • As a multi-statement closure, the body of the second is type-checked separately from the call to sort.

    • The types of the branches of the ternary operator must match, so it all gets type-checked together. We could probably separate out the checking for the condition, but we don't. The second version checks all three pieces separately, and uses the type pre-established by the call to sort.

  3. swift-ci commented on Feb 21, 2017

    @swift-ci
    Contributor

    Comment by Luis Grimaldo (JIRA)

    How come this does not have higher priority?
    Type-checking in general for Swift seems to be extremely slow.

  4. slavapestov commented on Sep 19, 2025

    @slavapestov
    Contributor

    This specific issue might be obsolete -- sort() is now sorted(), and Optional.< is gone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions