Repository navigation
perf: skip no-op UserDefaults writes on every session autosave #14822
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
Merged
teamleaderleo
merged 2 commits into
manaflow-ai:main
from
teamleaderleo:perf/autosave-skip-noop-defaults-writes
Sep 26, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
42 changes: 42 additions & 0 deletions
42
Packages/macOS/CmuxFoundation/Sources/CmuxFoundation/UserDefaults+ChangeOnlyWrites.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| public import Foundation | ||
|
|
||
| /// Writes that stay silent when the stored value already matches. | ||
| /// | ||
| /// `UserDefaults.set(_:forKey:)` and `removeObject(forKey:)` post | ||
| /// `UserDefaults.didChangeNotification` on every call, including writes that | ||
| /// store an identical value and removals of absent keys. That notification runs | ||
| /// every defaults observer in the process on the writing thread, including | ||
| /// SwiftUI's `@AppStorage` observer, which takes SwiftUI's global update lock | ||
| /// and so contends with main-thread rendering. Periodic writers (session | ||
| /// autosave) use these helpers so steady-state saves post nothing. | ||
| /// | ||
| /// The comparison reads through the normal search list, so a matching value in | ||
| /// the argument or registration domain also counts as unchanged. | ||
| extension UserDefaults { | ||
| /// Stores `value` for `key` unless the current value is byte-for-byte equal. | ||
| /// - Returns: `true` when a write happened. | ||
| @discardableResult | ||
| public func setIfChanged(_ value: Data, forKey key: String) -> Bool { | ||
| if data(forKey: key) == value { return false } | ||
| set(value, forKey: key) | ||
| return true | ||
| } | ||
|
|
||
| /// Stores `value` for `key` unless the current value is the same Boolean. | ||
| /// - Returns: `true` when a write happened. | ||
| @discardableResult | ||
| public func setIfChanged(_ value: Bool, forKey key: String) -> Bool { | ||
| if let current = object(forKey: key) as? Bool, current == value { return false } | ||
| set(value, forKey: key) | ||
| return true | ||
| } | ||
|
|
||
| /// Removes `key` only when a value is present. | ||
| /// - Returns: `true` when a removal happened. | ||
| @discardableResult | ||
| public func removeObjectIfPresent(forKey key: String) -> Bool { | ||
| guard object(forKey: key) != nil else { return false } | ||
| removeObject(forKey: key) | ||
| return true | ||
| } | ||
| } | ||
76 changes: 76 additions & 0 deletions
76
...es/macOS/CmuxFoundation/Tests/CmuxFoundationTests/UserDefaultsChangeOnlyWritesTests.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| import Foundation | ||
| import Testing | ||
|
|
||
| @testable import CmuxFoundation | ||
|
|
||
| /// Behavior tests for the change-only `UserDefaults` writers: each no-op write | ||
| /// must post no `didChangeNotification`, and real changes still post exactly one. | ||
| @Suite struct UserDefaultsChangeOnlyWritesTests { | ||
| @Test func dataWriteIsSilentWhenUnchanged() throws { | ||
| try withIsolatedDefaults { defaults, counter in | ||
| let payload = Data("geometry".utf8) | ||
| #expect(defaults.setIfChanged(payload, forKey: "k")) | ||
| #expect(counter.value == 1) | ||
| #expect(!defaults.setIfChanged(payload, forKey: "k")) | ||
| #expect(counter.value == 1) | ||
| #expect(defaults.setIfChanged(Data("moved".utf8), forKey: "k")) | ||
| #expect(counter.value == 2) | ||
| #expect(defaults.data(forKey: "k") == Data("moved".utf8)) | ||
| } | ||
| } | ||
|
|
||
| @Test func boolWriteIsSilentWhenUnchanged() throws { | ||
| try withIsolatedDefaults { defaults, counter in | ||
| #expect(defaults.setIfChanged(true, forKey: "flag")) | ||
| #expect(!defaults.setIfChanged(true, forKey: "flag")) | ||
| #expect(counter.value == 1) | ||
| #expect(defaults.setIfChanged(false, forKey: "flag")) | ||
| #expect(counter.value == 2) | ||
| #expect(defaults.object(forKey: "flag") as? Bool == false) | ||
| } | ||
| } | ||
|
|
||
| @Test func removalIsSilentWhenAbsent() throws { | ||
| try withIsolatedDefaults { defaults, counter in | ||
| #expect(!defaults.removeObjectIfPresent(forKey: "missing")) | ||
| #expect(counter.value == 0) | ||
| defaults.set("v", forKey: "present") | ||
| #expect(defaults.removeObjectIfPresent(forKey: "present")) | ||
| #expect(counter.value == 2) | ||
| #expect(defaults.object(forKey: "present") == nil) | ||
| } | ||
| } | ||
|
|
||
| private func withIsolatedDefaults( | ||
| _ body: (UserDefaults, NotificationTally) throws -> Void | ||
| ) throws { | ||
| let suiteName = "UserDefaultsChangeOnlyWritesTests.\(UUID().uuidString)" | ||
| let defaults = try #require(UserDefaults(suiteName: suiteName)) | ||
| defer { UserDefaults.standard.removePersistentDomain(forName: suiteName) } | ||
| let counter = NotificationTally() | ||
| let observer = NotificationCenter.default.addObserver( | ||
| forName: UserDefaults.didChangeNotification, | ||
| object: defaults, | ||
| queue: nil | ||
| ) { _ in counter.increment() } | ||
| defer { NotificationCenter.default.removeObserver(observer) } | ||
| try body(defaults, counter) | ||
| } | ||
| } | ||
|
|
||
| private final class NotificationTally: @unchecked Sendable { | ||
| private let lock = NSLock() | ||
| private var count = 0 | ||
|
|
||
| var value: Int { | ||
| lock.lock() | ||
| defer { lock.unlock() } | ||
| return count | ||
| } | ||
|
|
||
| func increment() { | ||
| lock.lock() | ||
| count += 1 | ||
| lock.unlock() | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Check the persistent domain before reporting a removal.
If a key exists only in the registration or argument domain,
object(forKey:)passes this guard, butremoveObject(forKey:)has no persisted value to remove. The helper then reports a removal and can repeat a no-op defaults mutation on every call. The structural issue is using the effective value as the source of truth for persisted-key presence. Make target-domain presence the removal invariant. As a first migration cut, add a test with a registered fallback and no persisted value, then make the helper returnfalsewithout removing that key. (developer.apple.com)As per coding guidelines, Swift fixes must address the state invariant rather than only one repro.
🤖 Prompt for AI Agents
Source: Coding guidelines