Performance

How the x86-64 backend generates code, and where the time goes.

vlatest

What the backend does

PickleIR reaches the x86-64 backend, which does the code generation. The settings that are set are about code model and compile time. See Backends.

Optional narrowing

The backend narrows optionals during lowering rather than re-checking them at run time. These are the steps that make it work:

Step What it does
optIsPresent Answers "is this optional known to be some?"
optUnwrap / optUnwrapVal Drops the optional wrapper when the value is statically present
optResolve Resolves the payload type of an optional
optAccess / optMemberRead Reads a field or member through a narrowed optional

The pattern they implement is what lets a narrowed optional be read without a repeated wrapper check. There is no if let, so narrowing happens in a match:

class Counter {
    var total: int

    constructor() {
        this.total = 0
    }
}

fn describe(c: Counter?) -> int {
    match (c) {
        case some(v) -> { return v.total }
        case none -> { return 0 }
    }
}

fn main() {
    println(describe(Counter()))
}

Inside the case some(v) arm the compiler already knows the value is present, so v.total is a direct field read rather than a load followed by a test. The none arm is where a runtime check would be required, and it is the arm that never runs.

Practical advice

  • Measure before optimising. With no profiler, the honest options are timing the program end to end and bisecting with pickle check.
  • pickle check is the fast loop. Type checking never reaches code generation.
  • A hot loop in a for over a range is fine. Ranges lower to plain arithmetic and a branch; there is no iterator protocol to pay for.
  • Do not expect the JIT and a built binary to perform alike. A built binary is a separate compilation path with its own costs. See Backends.