Skip to content

Instantly share code, notes, and snippets.

@simonbs
Last active December 20, 2024 19:34
Show Gist options
  • Save simonbs/3e5d6877d6e67648dac5932189ea3ff3 to your computer and use it in GitHub Desktop.
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.
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()
}
}
}
}
@simonbs
Copy link
Author

simonbs commented Dec 20, 2024

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.

graphs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment