Skip to content

Commit

Permalink
Use a Set to process and deduplicate fields.
Browse files Browse the repository at this point in the history
Although this may seem like a reversion to forEach instead of a for loop,
the for loop had an unexpectedly negative impact on minification, and a
Set has the ability to deduplicate selection objects, so we never
re-process the same field multiple times through different fragments.
  • Loading branch information
benjamn committed Feb 16, 2020
1 parent df20ff5 commit dc61865
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 18 deletions.
14 changes: 5 additions & 9 deletions src/cache/inmemory/readFromStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,16 +222,12 @@ export class StoreReader {
return result.result;
}

const selections = selectionSet.selections.slice(0);

// Reevaluating selections.length each time is important, because we
// add additional selections in the fragment case below.
for (let s = 0; s < selections.length; ++s) {
const selection = selections[s];
const workSet = new Set(selectionSet.selections);

workSet.forEach(selection => {
// Omit fields with directives @skip(if: <truthy value>) or
// @include(if: <falsy value>).
if (!shouldInclude(selection, variables)) continue;
if (!shouldInclude(selection, variables)) return;

if (isField(selection)) {
let fieldValue = policies.readField(
Expand Down Expand Up @@ -305,10 +301,10 @@ export class StoreReader {
}

if (policies.fragmentMatches(fragment, typename)) {
selections.push(...fragment.selectionSet.selections);
fragment.selectionSet.selections.forEach(workSet.add, workSet);
}
}
}
});

// Perform a single merge at the end so that we can avoid making more
// defensive shallow copies than necessary.
Expand Down
14 changes: 5 additions & 9 deletions src/cache/inmemory/writeToStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,14 +183,10 @@ export class StoreWriter {
}

const { policies } = this;
const selections = selectionSet.selections.slice(0);
const workSet = new Set(selectionSet.selections);

// Reevaluating selections.length each time is important, because we
// add additional selections in the fragment case below.
for (let s = 0; s < selections.length; ++s) {
const selection = selections[s];

if (!shouldInclude(selection, context.variables)) continue;
workSet.forEach(selection => {
if (!shouldInclude(selection, context.variables)) return;

if (isField(selection)) {
const resultFieldKey = resultKeyNameFromField(selection);
Expand Down Expand Up @@ -255,10 +251,10 @@ export class StoreWriter {
);

if (policies.fragmentMatches(fragment, typename)) {
selections.push(...fragment.selectionSet.selections);
fragment.selectionSet.selections.forEach(workSet.add, workSet);
}
}
}
});

return mergedFields;
}
Expand Down

0 comments on commit dc61865

Please sign in to comment.