Skip to content

Commit

Permalink
[Performance Issue] Use dictionary to manage subscribers (#439)
Browse files Browse the repository at this point in the history
  • Loading branch information
muukii authored Oct 26, 2023
1 parent 654458d commit b7d83ba
Showing 1 changed file with 5 additions and 18 deletions.
23 changes: 5 additions & 18 deletions Sources/Verge/Library/EventEmitter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,7 @@ open class EventEmitter<Event>: EventEmitterType, @unchecked Sendable {
return .init(eventEmitter: self)
}

/**
The reason why we use array against dictionary, the subscribers does not often remove.
*/
private var subscribers:
VergeConcurrency.UnfairLockAtomic<[(EventEmitterCancellable, (Event) -> Void)]> = .init([])
private var subscribers: VergeConcurrency.UnfairLockAtomic<[EventEmitterCancellable : (Event) -> Void]> = .init([:])

private let queue: VergeConcurrency.UnfairLockAtomic<Deque<Event>> = .init(.init())

Expand Down Expand Up @@ -135,25 +131,16 @@ open class EventEmitter<Event>: EventEmitterType, @unchecked Sendable {
public func addEventHandler(_ eventReceiver: @escaping (Event) -> Void) -> EventEmitterCancellable {
let token = EventEmitterCancellable(owner: self)
subscribers.modify {
$0.append((token, eventReceiver))
$0[token] = eventReceiver
}
return token
}

func removeEventHandler(_ token: EventEmitterCancellable) {
var itemToRemove: (EventEmitterCancellable, (Event) -> Void)? = nil
var itemToRemove: ((Event) -> Void)? = nil
subscribers.modify {
$0.removeAll {
if $0.0 == token {
if itemToRemove == nil {
itemToRemove = $0
} else {
assertionFailure("found two or more values")
}
return true
}
return false
}
itemToRemove = $0[token]
$0.removeValue(forKey: token)
}

// To avoid triggering deinit inside removing operation
Expand Down

0 comments on commit b7d83ba

Please sign in to comment.