Could `Data` ship a "fast path" check for identity equality?

I confirm OP results with a totally different test

Simple test
var eqCount = 0
let k = 10000
for i in 0 ..< k {
    let n = 100_000 * I
    let data = Data(repeating: 0, count: n)
    let data2 = data
    let start = Date()
    eqCount += data == data2 ? 1 : 0
    let elapsed = Date().timeIntervalSince(start)
    print(n, elapsed * 1000, "ms")
}
precondition(eqCount == k)

Did it on macOS to see if it's Foundation implementation behaves differently in this case - no, it's still O(n) there.


You could see more details in another thread, but in a nutshell – no, it shouldn't be like this. Besides other things it makes a vector of DoS attack possible, a similar one to what hash randomisation is solving.

var data = Data(repeating: 0, count: 81)
data[data.count - 1] = 1
let a = data.hashValue
data[data.count - 1] = 2
let b = data.hashValue
print(a, b, a == b) // 7025483855299775759 7025483855299775759 true

You could see it here and it is the same behaviour on Apple's version of Foundation used on macOS/iOS.

2 Likes