Skip to content

[SR-10708] switch over Dictionary lookup retains ref count #53105

Open
@drexin

Description

@drexin
Previous ID SR-10708
Radar None
Original Reporter @drexin
Type Bug

Attachment: Download

Environment

Apple Swift version 5.0 (swift-5.0-RELEASE)
Target: x86_64-apple-darwin18.5.0

Additional Detail from JIRA
Votes 1
Component/s Compiler
Labels Bug, 5.0Regression, ARC, Optimizer
Assignee None
Priority Medium

md5: c994e96b09804105727b513a51ebc355

relates to:

  • SR-10709 Swift needs allocation counter tests

Issue Description:

When switching over the result of a dictionary lookup directly in Swift 5 and then modifying that dictionary it will be copied.

class Foo {
    var dict: [String: Int] = ["x": 1]


    func test(_ x: String) {
        switch dict[x] {
        case .some(let y):
            dict[x] = y
        default: ()
        }
    }
}


let foo = Foo()

for _ in 1 ... 1000 {
    foo.test("x")
}

The above code allocates 1092 times in total.

When assigning the result to a variable first, it does not copy.

class Foo {
    var dict: [String: Int] = ["x": 1]


    func test(_ x: String) {
        let value = dict[x]
        switch value {
        case .some(let y):
            dict[x] = y
        default: ()
        }
    }
}


let foo = Foo()

for _ in 1 ... 1000 {
    foo.test("x")
}

The above code allocates 91 times in total.

In Swift 4.2 both versions do not copy, so this seems to be a regression in Swift 5.

Metadata

Metadata

Assignees

No one assigned

    Labels

    ARCFeature: automatic reference countingSILOptimizerArea → compiler: SIL optimization passesbugA deviation from expected or documented behavior. Also: expected but undesirable behavior.compilerThe Swift compiler itselfregressionstandard libraryArea: Standard library umbrellaswift 5.0

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions