简体   繁体   中英

My react event pooling pseudo example makes sense?

TLDR

Can I check about implementation about event pooling logic in react.
And I want to know about event pooling principle:)

Question

When I deep dive to react document, I see about event pooling .
So, I'm so curious about what is event pooling and I research about it.

And now I realize about thread pooling . So it is working similarly. So I make some pseudo event pooling logic.
And I want to know it does make sense?

And any one who know about where event pooling implementation is in react package.
Just comment to me please

Pseudo event pooling

EventPool pseudo implementation

class EventPool {
  private static instance: EventPool;
  private taskQueue: Event[] = [];
  private constructor() {
    this.taskQueue = [];
  }

  public static shared() {
    if (!EventPool.instance) {
      EventPool.instance = new EventPool();
    }
    return EventPool.instance;
  }

  enqueue = (event: Event) => {
    this.taskQueue = this.taskQueue.concat(event);
  };

  dequeue = (currentTarget: any) => {
    this.taskQueue = this.taskQueue.filter(
      (event: Event) => event.currentTarget === currentTarget
    );
  };

  clear() {
    // This function called before or after render 
    // (Commit -> Render -> EventPool.shared().clear()) or (Commit -> EventPool.shared().clear() -> Render) 
    this.taskQueue = this.taskQueue.filter((event) => event.isDone === true);
  }
}

Event pseudo implementation about persist

class Event {
  persist = () => {
    // This is executed before EventPool.shared.clear
    EventPool.shared().dequeue(this);
  };
}

Reference

  1. What is event pooling in react? - StackOverflow
  2. Synthetic Event - React Document
  3. What's the meaning of Event Pooling?
  4. 진보된 쓰레드 풀링 기법 구현 - Korean

Here is quite simple example of SyntheticEvent / EventPool pattern. Obviously in real life it'll be a bit more complex to better respect of event's behavior, but this snippet have to shed some light on concept.

class SyntheticEvent {
    // all the following properties and methods are part of React's
    // synthetic event, but we'll skip it here in favor of simplicity

    // bubbles: boolean
    // currentTarget: DOMEventTarget
    // defaultPrevented: boolean
    // eventPhase: number
    // nativeEvent: DOMEvent
    // preventDefault(): void {}
    // isDefaultPrevented(): boolean { return true }
    // stopPropagation(): void {}
    // isPropagationStopped(): boolean { return true }
    // target: DOMEventTarget
    // timeStamp: number
    // type: string

    // for simplicity we'll consider here only 3 following properties
    isTrusted: boolean
    cancelable: boolean
    persist: () => void

    // this property helps to track status of each synthetic event
    status: 'POOLED' | 'PERSISTED' | 'IN_USE'

    constructor(status, onPersist: () => void) {
        this.status = status;
        this.persist = onPersist;
    }
}

class EventPool {
    private pool: SyntheticEvent[] = [];

    constructor(initialPoolSize: number) {
        // populating pool with pre-allocated events. We will try to re-use
        // them as much as possible to reduce GC load
        for(let i = 0; i < initialPoolSize; i++) {
            this.allocateNewEvent();
        }
    }

    pullEvent(nativeEvent): SyntheticEvent {
        const syntheticEvent = this.getEventFromPool();
        this.populateEvent(syntheticEvent, nativeEvent);
        return syntheticEvent;
    }

    tryPushEvent(syntheticEvent: SyntheticEvent): void {
        if(syntheticEvent.status !== 'PERSISTED') {
            this.clearEvent(syntheticEvent);
        }
    }


    private allocateNewEvent(): SyntheticEvent {
        const newEvent = new SyntheticEvent( 'POOLED', () => {
            newEvent.status = 'PERSISTED';
        });
        this.pool.push(newEvent);
        return newEvent;
    }

    private getEventFromPool() {
        let event = this.pool.find( e => e.status === 'POOLED' );
        if(!event) {
            event = this.allocateNewEvent();
        }

        return event;
    }

    /** Populates synthetic event with data from native event */
    private populateEvent(syntheticEvent: SyntheticEvent, nativeEvent) {
        syntheticEvent.status = 'IN_USE';
        syntheticEvent.isTrusted = nativeEvent.isTrusted;
        syntheticEvent.cancelable = nativeEvent.cancelable;
    }

    /** Sets all previously populated synthetic event fields to null for safe re-use */
    private clearEvent(syntheticEvent: SyntheticEvent) {
        syntheticEvent.status = 'POOLED';
        syntheticEvent.isTrusted = null;
        syntheticEvent.cancelable = null;
    }
}

// Usage
const mainEventPool = new EventPool(2);
smth.onClick = nativeEvent => {
    const syntheticEvent = mainEventPool.pullEvent(nativeEvent);
    userDefinedOnClickHandler(syntheticEvent); // <-- on click handler defined by user
    mainEventPool.tryPushEvent(syntheticEvent);
};

Event Pooling - React uses SyntheticEvent which is a wrapper for native browser events so that they have consistent properties across different browsers. The event handlers that we have in any react-app are actually passed instances of SyntheticEvent unless we use nativeEvent attribute to get the underlying browser event.

Wrapping native event instances can cause performance issues since every synthetic event wrapper that's created will also need to be garbage collected at some point, which can be expensive in terms of CPU time.

React deals with this problem by allocating a synthetic instance pool. Whenever an event is triggered, it takes an instance from the pool and populates its properties and reuses it. When the event handler has finished running, all properties will be nullified and the synthetic event instance is released back into the pool. Hence, increasing the performance.

https://stackoverflow.com/a/53500357/1040070

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM