Skip to content

Commit

Permalink
perf(client): Memoize message parsing for each subscriber
Browse files Browse the repository at this point in the history
  • Loading branch information
enisdenjo committed Sep 11, 2020
1 parent 6af2887 commit 2a7ba46
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/client.ts
Expand Up @@ -9,6 +9,7 @@
import { Sink, UUID, Disposable } from './types';
import { GRAPHQL_TRANSPORT_WS_PROTOCOL } from './protocol';
import {
Message,
MessageType,
parseMessage,
stringifyMessage,
Expand Down Expand Up @@ -363,13 +364,24 @@ export function createClient(options: ClientOptions): Client {
})();
}

// to avoid parsing the same message in each
// subscriber, we memo one on the last received data
let lastData: unknown, lastMessage: Message;
function memoParseMessage(data: unknown) {
if (data !== lastData) {
lastMessage = parseMessage(data);
}
lastData = data;
return lastMessage;
}

return {
on: emitter.on,
subscribe(payload, sink) {
const uuid = generateUUID();

const messageHandler = ({ data }: MessageEvent) => {
const message = parseMessage(data);
const message = memoParseMessage(data);
switch (message.type) {
case MessageType.Next: {
if (message.id === uuid) {
Expand Down

0 comments on commit 2a7ba46

Please sign in to comment.