Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve cache serialization performance by 30% #12955

Merged
merged 1 commit into from
Mar 23, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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