tokopedia / RxComposableArchitecture

RxComposableArchitecture is a forked of Composable Architecture with adjustment to make it work with UIKit.
Apache License 2.0
31 stars 5 forks source link

Improve performance of type-safe effect cancel token lookup #47

Closed ivanbagaskara closed 2 years ago

ivanbagaskara commented 2 years ago

Our current recommendation of using a dedicated type for effect cancel tokens unfortunately leads to the equivalent of a linear search due to Swift's default hashing behavior:

struct A: Hashable {}
struct B: Hashable {}

A().hashValue == B().hashValue // true

This PR introduces an internal wrapper type that includes the type's unique identifier in the hashing logic, which should improve the hashing of these identifiers:

struct CancelToken: Hashable {
  let id: AnyHashable
  let discriminator: ObjectIdentifier

  init(id: AnyHashable) {
    self.id = id
    self.discriminator = ObjectIdentifier(type(of: id.base))
  }
}

CancelToken(id: A()).hashValue == CancelToken(id: A()).hashValue // true
CancelToken(id: B()).hashValue == CancelToken(id: B()).hashValue // true
CancelToken(id: A()).hashValue == CancelToken(id: B()).hashValue // false