Last active
December 20, 2024 19:34
-
-
Save simonbs/3e5d6877d6e67648dac5932189ea3ff3 to your computer and use it in GitHub Desktop.
Example app reproducing an issue where memory usage increases linearly when continuously accessing an Observable object.
This file contains 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
import Observation | |
import SwiftUI | |
// ⚠️ Referencing ObservableSettings.isEnabled causes memory to pile up. | |
@Observable | |
final class ObservableSettings { | |
var isEnabled = true | |
} | |
// Referencing NonObservableSettings.isEnabled causes memory usage to be stable. | |
final class NonObservableSettings { | |
var isEnabled = true | |
} | |
@main | |
struct ExampleApp: App { | |
private let settings = NonObservableSettings() // 👈 Use ObservableSettings or NonObservableSettings. | |
var body: some Scene { | |
WindowGroup { | |
ContentView(settings: settings) | |
} | |
} | |
} | |
struct ContentView: View { | |
let settings: NonObservableSettings // 👈 Use ObservableSettings or NonObservableSettings. | |
@State private var date = Date() | |
var body: some View { | |
VStack { | |
Text("Is Enabled: " + (settings.isEnabled ? "✅" : "⬛")) | |
Text(date, format: .dateTime.hour().minute().second()) | |
} | |
.task { | |
while true { | |
try? await Task.sleep(for: .seconds(0.01)) | |
date = Date() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is now confirmed to be a bug in SwiftUI. bsky.app/profile/duan.ca/post/…
I've filed this as feedback to Apple. You can find the feedback along with an example project here: https://github.com/simonbs/AppleFeedback/blob/main/FB16123942
For reference, here's the memory graphs produced by the example code.