From 8c7718e38357d451ed0977ea0cd9d42dcc4ca0cf Mon Sep 17 00:00:00 2001 From: codytseng Date: Sun, 31 Mar 2024 17:17:06 +0800 Subject: [PATCH] perf(ws): optimize message handler lookup --- packages/platform-ws/adapters/ws-adapter.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/packages/platform-ws/adapters/ws-adapter.ts b/packages/platform-ws/adapters/ws-adapter.ts index 770a5f9963a..f8b51091353 100644 --- a/packages/platform-ws/adapters/ws-adapter.ts +++ b/packages/platform-ws/adapters/ws-adapter.ts @@ -111,10 +111,13 @@ export class WsAdapter extends AbstractWsAdapter { handlers: MessageMappingProperties[], transform: (data: any) => Observable, ) { + const handlersMap = new Map(); + handlers.forEach(handler => handlersMap.set(handler.message, handler)); + const close$ = fromEvent(client, CLOSE_EVENT).pipe(share(), first()); const source$ = fromEvent(client, 'message').pipe( mergeMap(data => - this.bindMessageHandler(data, handlers, transform).pipe( + this.bindMessageHandler(data, handlersMap, transform).pipe( filter(result => !isNil(result)), ), ), @@ -131,14 +134,12 @@ export class WsAdapter extends AbstractWsAdapter { public bindMessageHandler( buffer: any, - handlers: MessageMappingProperties[], + handlersMap: Map, transform: (data: any) => Observable, ): Observable { try { const message = JSON.parse(buffer.data); - const messageHandler = handlers.find( - handler => handler.message === message.event, - ); + const messageHandler = handlersMap.get(message.event); const { callback } = messageHandler; return transform(callback(message.data, message.event)); } catch {