Skip to content

Instantly share code, notes, and snippets.

@banjun
Created February 4, 2025 04:27
Show Gist options
  • Save banjun/fca00a6208ffed2956e3af9f06183a03 to your computer and use it in GitHub Desktop.
Save banjun/fca00a6208ffed2956e3af9f06183a03 to your computer and use it in GitHub Desktop.
SwiftUI & Observation memory leaks
import SwiftUI
import Observation
// Leaks Malloc 48 Bytes block, 144 Bytes block, 128 Bytes block on macOS 15.3 (24D60), Xcode 16.2 (16C5032a)
// leaks speed is ~ +10MB / 5 mins, with Instruments
@main
struct SwiftUIObservationLeaksApp: App {
@State private var model: Model = .init()
@MainActor @Observable final class Model {
var items: [Item] = [.init(), .init(), .init()]
struct Item: Hashable, Identifiable {
var id = UUID()
}
}
@State private var count: Int = 0
struct V: View {
var count: Int
var body: some View {
EmptyView()
}
}
var body: some Scene {
WindowGroup {
V(count: count) // dummy view, that does not use the arg value in its body
ForEach(model.items) { item in
Text("\(String(describing: model.items))") // access ObservationTracking in ForEach
}
.task {
while true {
try! await Task.sleep(for: .milliseconds(10))
count += 1
}
}
}
}
}
@banjun
Copy link
Author

banjun commented Feb 4, 2025

image

@banjun
Copy link
Author

banjun commented Feb 4, 2025

FB16444878

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