pointfreeco / swift-perception

Observable tools, backported.
MIT License
575 stars 44 forks source link

The array tracked will become very slow when access #98

Closed yoodu closed 2 months ago

yoodu commented 2 months ago

Description

The code example is as follows. When using @Observable, it runs quickly

@Perceptible
final class AssetRow {
  var data: [Int] = []

  init(_ data: [Int]) {
    self.data = data
  }
}

print(Date(), 1)
let arr = (1 ... 3000).map { _ in AssetRow([]) }
print(Date(), 2)
let _ = arr.map { $0.data.count } // very slow
print(Date(), 3)

Result: 2024-09-15 14:04:16 +0000 1 2024-09-15 14:04:16 +0000 2 2024-09-15 14:04:22 +0000 3

Checklist

Expected behavior

No response

Actual behavior

No response

Steps to reproduce

No response

Perception version information

No response

Destination operating system

No response

Xcode version information

No response

Swift Compiler version information

No response

mbrandonw commented 2 months ago

Hi @yoodu, this is only true in debug builds because of the additional perception checks we perform at runtime. We try to detect when you access a field of a @Perceptible model while inside a view's body but not inside WithPerceptionTracking. Those checks do take some work, but they are only run in debug. If you run your code in release you will find that there is no difference between @Perceptible and @Observable. And if you have ideas of how to speed up those checks we would happily take a PR.

Since this isn't an issue with the library I am going to convert it to a discussion. Please feel free to continue the conversation over there!