Skip to content

Commit

Permalink
Merge pull request #12955 from webpack/perf/serialize
Browse files Browse the repository at this point in the history
improve cache serialization performance by 30%
  • Loading branch information
sokra committed Mar 23, 2021
2 parents 1c044bc + 3f378d9 commit 318a73e
Showing 1 changed file with 25 additions and 12 deletions.
37 changes: 25 additions & 12 deletions lib/serialization/ObjectMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -408,16 +408,13 @@ class ObjectMiddleware extends SerializerMiddleware {
};
this.extendContext(ctx);
const process = item => {
// check if we can emit a reference
const ref = referenceable.get(item);

if (ref !== undefined) {
result.push(ESCAPE, ref - currentPos);

return;
}

if (Buffer.isBuffer(item)) {
// check if we can emit a reference
const ref = referenceable.get(item);
if (ref !== undefined) {
result.push(ESCAPE, ref - currentPos);
return;
}
const alreadyUsedBuffer = dedupeBuffer(item);
if (alreadyUsedBuffer !== item) {
const ref = referenceable.get(alreadyUsedBuffer);
Expand All @@ -431,7 +428,19 @@ class ObjectMiddleware extends SerializerMiddleware {
addReferenceable(item);

result.push(item);
} else if (typeof item === "object" && item !== null) {
} else if (item === ESCAPE) {
result.push(ESCAPE, ESCAPE_ESCAPE_VALUE);
} else if (
typeof item === "object"
// We don't have to check for null as ESCAPE is null and this has been checked before
) {
// check if we can emit a reference
const ref = referenceable.get(item);
if (ref !== undefined) {
result.push(ESCAPE, ref - currentPos);
return;
}

if (cycleStack.has(item)) {
throw new Error(`Circular references can't be serialized`);
}
Expand Down Expand Up @@ -464,6 +473,12 @@ class ObjectMiddleware extends SerializerMiddleware {
} else if (typeof item === "string") {
if (item.length > 1) {
// short strings are shorter when not emitting a reference (this saves 1 byte per empty string)
// check if we can emit a reference
const ref = referenceable.get(item);
if (ref !== undefined) {
result.push(ESCAPE, ref - currentPos);
return;
}
addReferenceable(item);
}

Expand All @@ -476,8 +491,6 @@ class ObjectMiddleware extends SerializerMiddleware {
}

result.push(item);
} else if (item === ESCAPE) {
result.push(ESCAPE, ESCAPE_ESCAPE_VALUE);
} else if (typeof item === "function") {
if (!SerializerMiddleware.isLazy(item))
throw new Error("Unexpected function " + item);
Expand Down

0 comments on commit 318a73e

Please sign in to comment.