@Observable pessimizes arrays

It's not quadratic, it's linear... This is what I am getting for @Observable:

It shows time (in seconds) of adding 100K elements depending upon how many elements are in the array already.

Interestingly I'm getting exactly the same behaviour for ObservableObject + Published.
Ditto for this manual code:

class Model2 {
    static var changeCount = 0
    
    var array: [Int] = [] {
        didSet {
            if array != oldValue { Self.changeCount += 1}
        }
    }
}

or this:

        didSet {
            if array.count != oldValue.count { Self.changeCount += 1}
        }

But not this!

        didSet { Self.changeCount &+= array.count }

or simply:

        didSet { Self.changeCount += 1 }

The crucial difference: is "oldValue" being accessed or not. I guess the reason of the slowdown is this: if you are accessing "oldValue" Swift is providing you with a copy, and this is the time to make this copy is what we see in the timing plot.

I hope this finding could bring us closer to the actual fix.

1 Like