Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SR-5258] Mutating a dictionary's value through Dictionary.Values still leads to copying #47833

Closed
hamishknight opened this issue Jun 19, 2017 · 5 comments
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. performance standard library Area: Standard library umbrella

Comments

@hamishknight
Copy link
Collaborator

Previous ID SR-5258
Radar rdar://problem/44725826
Original Reporter @hamishknight
Type Bug
Status Resolved
Resolution Done
Environment

Apple Swift version 4.0 (swiftlang-900.0.43 clang-900.0.22.8)
Target: x86_64-apple-macosx10.9

Additional Detail from JIRA
Votes 1
Component/s Standard Library
Labels Bug, Performance
Assignee None
Priority Medium

md5: 220947852a5790211c5a2c1347785438

Issue Description:

As I understand it, one of the motivations behind SE-0154 (https://github.com/apple/swift-evolution/blob/master/proposals/0154-dictionary-key-and-value-collections.md) was to eliminate the unnecessary copying of a dictionary's value upon mutating it.

However this still appears to be the case:

class Buffer {
    var value: Int
    init(value: Int = 0) { self.value = value }
}

struct COWStruct {
    
    private var buffer = Buffer()
    
    mutating func change() {
        if isKnownUniquelyReferenced(&buffer) {
            buffer.value += 1
            print("No copy")
        } else {
            buffer = Buffer(value: buffer.value + 1)
            print("Copy")
        }
    }
}

var dict = ["key": COWStruct()]

if let index = dict.index(forKey: "key") {
    dict.values[index].change() // Copy
}

Looks like both the Dictionary and Dictionary.Values instances have a view onto the underlying buffer, therefore triggering a copy upon the subscript accessor being called.

@moiseev
Copy link
Mannequin

moiseev mannequin commented Aug 18, 2017

cc @natecook1000

@hamishknight
Copy link
Collaborator Author

@lorentey has opened a PR which should fix this – #19497 🙂

@lorentey
Copy link
Member

Thanks Hamish! I knew there was a bug for this somewhere 🙂

@lorentey
Copy link
Member

@swift-ci create

@lorentey
Copy link
Member

Fixed on master by defining a _modify accessor for Dictionary.values.

@swift-ci swift-ci transferred this issue from apple/swift-issues Apr 25, 2022
This issue was closed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. performance standard library Area: Standard library umbrella
Projects
None yet
Development

No branches or pull requests

2 participants