Skip to content

Commit f1c30e9

Browse files
committed
use WeakMap to manage sets to reclaim memory as possible
1 parent 5818ce8 commit f1c30e9

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

src/execution/execute.ts

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ import { GraphQLStreamDirective } from '../type/directives.js';
4848
import type { GraphQLSchema } from '../type/schema.js';
4949
import { assertValidSchema } from '../type/validate.js';
5050

51-
import type { TaggedFieldNode } from './collectFields.js';
51+
import type { GroupedFieldSet, TaggedFieldNode } from './collectFields.js';
5252
import {
5353
collectFields,
5454
collectSubfields as _collectSubfields,
@@ -123,7 +123,7 @@ export interface ExecutionContext {
123123
subscribeFieldResolver: GraphQLFieldResolver<any, any>;
124124
errors: Array<GraphQLError>;
125125
subsequentPayloads: Set<AsyncPayloadRecord>;
126-
branches: Set<string>;
126+
branches: WeakMap<GroupedFieldSet, Set<string>>;
127127
}
128128

129129
/**
@@ -502,7 +502,7 @@ export function buildExecutionContext(
502502
typeResolver: typeResolver ?? defaultTypeResolver,
503503
subscribeFieldResolver: subscribeFieldResolver ?? defaultFieldResolver,
504504
subsequentPayloads: new Set(),
505-
branches: new Set(),
505+
branches: new WeakMap(),
506506
errors: [],
507507
};
508508
}
@@ -515,18 +515,24 @@ function buildPerEventExecutionContext(
515515
...exeContext,
516516
rootValue: payload,
517517
subsequentPayloads: new Set(),
518-
branches: new Set(),
518+
branches: new WeakMap(),
519519
errors: [],
520520
};
521521
}
522522

523523
function shouldBranch(
524524
exeContext: ExecutionContext,
525+
groupedFieldSet: GroupedFieldSet,
525526
path: Path | undefined,
526527
): boolean {
528+
const set = exeContext.branches.get(groupedFieldSet);
527529
const key = pathToArray(path).join('.');
528-
if (!exeContext.branches.has(key)) {
529-
exeContext.branches.add(key);
530+
if (set === undefined) {
531+
exeContext.branches.set(groupedFieldSet, new Set([key]));
532+
return true;
533+
}
534+
if (!set.has(key)) {
535+
set.add(key);
530536
return true;
531537
}
532538
return false;
@@ -591,7 +597,10 @@ function executeOperation(
591597
);
592598
}
593599

594-
if (newDeferDepth !== undefined && shouldBranch(exeContext, path)) {
600+
if (
601+
newDeferDepth !== undefined &&
602+
shouldBranch(exeContext, groupedFieldSet, path)
603+
) {
595604
executeDeferredFragment(
596605
exeContext,
597606
rootType,
@@ -1587,7 +1596,10 @@ function collectAndExecuteSubfields(
15871596
asyncPayloadRecord,
15881597
);
15891598

1590-
if (newDeferDepth !== undefined && shouldBranch(exeContext, path)) {
1599+
if (
1600+
newDeferDepth !== undefined &&
1601+
shouldBranch(exeContext, groupedFieldSet, path)
1602+
) {
15911603
executeDeferredFragment(
15921604
exeContext,
15931605
returnType,

0 commit comments

Comments
 (0)