Created
February 4, 2025 04:27
-
-
Save banjun/fca00a6208ffed2956e3af9f06183a03 to your computer and use it in GitHub Desktop.
SwiftUI & Observation memory leaks
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
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 | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment