How-To Guide

How to Optimize JSON Serialization

Speed up JSON work: stream instead of buffering, avoid redundant stringify and parse, and pick a serializer that fits the payload.

On this page

  1. Introduction
  2. Stream large payloads instead of buffering
  3. Avoid redundant conversions
  4. Choose a serializer for the shape
  5. Measure size and time
  6. Test bounded memory and time
  7. Common pitfalls
  8. Conclusion

Introduction

JSON is the default interchange format and rarely the first thing people optimize, yet serialization can dominate a hot path. Building a large object into a single string allocates memory proportional to the payload, and the string is then copied again to send it. Doing it twice, as when a value is stringified, parsed, and stringified again, doubles the cost for no benefit. On a high-rate endpoint, this work adds up to a measurable CPU and latency cost.

This tutorial optimizes JSON serialization: stream large payloads instead of buffering them whole, avoid redundant stringify and parse, choose a serializer that fits the shape, and measure size and time. The examples use Node.js and Python, and the reasoning applies to any runtime.

Stream large payloads instead of buffering

A response that builds the entire JSON in memory before sending allocates a string as large as the payload and holds it until the write completes. For a large list, that peak is avoidable: serialize element by element and write each to the response as it is produced, so memory stays proportional to one element rather than the whole list. The client starts receiving bytes sooner, which also improves the time to first byte.

Streaming also lets the query produce rows and the response emit them incrementally, so the server does not hold both the result set and the serialized string. Use the runtime’s streaming encoder to write a JSON array as a sequence of encoded elements, with the delimiters written once. The result is the same JSON, produced in bounded memory.

import { createServer } from 'node:http';

createServer(async (req, res) => {
  res.writeHead(200, { 'content-type': 'application/json' });
  res.write('[');
  let first = true;
  for await (const row of streamRows()) {          // rows arrive incrementally
    if (!first) res.write(',');
    res.write(JSON.stringify(row));                // serialize one element at a time
    first = false;
  }
  res.end(']');
}).listen(3000);

Avoid redundant conversions

Each JSON.stringify allocates and walks the whole value, and each JSON.parse reconstructs it. A pipeline that parses then re-stringifies, or that stringifies a value only to parse it in the next function, pays twice. Keep a value in one representation until the boundary where it must become bytes, and parse once when bytes enter. Look for round trips that cross the same boundary repeatedly.

A common inefficiency is deep-cloning a value with stringify and parse when a structured clone or a shallow copy would do. Another is validating a value by stringifying it. Both add allocations proportional to the payload for no functional gain. Prefer operations that do not serialize: a shallow copy for a plain object, a structured clone for a complex one, and a direct check for validation.

// wasteful: serialize and reparse just to clone
const clone = structuredClone(value);   // instead of JSON.parse(JSON.stringify(value))

// wasteful: stringify then parse in the next layer
// keep the object and serialize only at the response boundary, once

Choose a serializer for the shape

The platform encoder is fine for general use and adds no dependency. When the same shape is serialized many times on a hot path, a schema-driven or compiled encoder that knows the field names at build time avoids re-deriving them per call and can be several times faster. This is worth it only on a measured hot path, where the serialization time is a significant fraction of the request.

Also consider the wire format. If both ends control the format and the payload is large, a more compact encoding than JSON reduces the bytes and the serialization cost. But JSON is interoperable and debuggable, so switch only where the benefit is measured. The decision is a trade of speed for interoperability, and it should be made on data, not on principle.

import json

# general path: the standard library encoder is fine
payload = json.dumps(obj)

# hot path with a fixed shape: a compiled encoder avoids re-deriving field names
# from orjson import dumps  # example of a faster library, chosen after measuring
# payload = dumps(obj)

Measure size and time

Measure the serialized size and the time to serialize a representative payload before and after a change, and measure the peak memory for a streamed versus a buffered response. A change that is faster but harder to maintain is worth it only where the measurement shows a real gain. The peak memory of a streamed large list should stay flat as the list grows, which a buffered version cannot.

Watch for the case where the optimization is not in serialization at all. If the endpoint is slow, the cause may be the query or a downstream call, not the JSON. Profile before optimizing, and keep the serialization change if it shows up in the profile. An optimization that does not move a measured metric is complexity without benefit.

# time and size of a representative payload
node -e '
const obj = makeLargeObject();
const t0 = process.hrtime.bigint();
const s = JSON.stringify(obj);
console.log("bytes=" + s.length, "ms=" + Number(process.hrtime.bigint()-t0)/1e6);
'

Test bounded memory and time

Test that a streamed response to a large list keeps peak memory bounded as the list grows, by doubling the list and asserting the peak does not double. Test that no path serializes and parses the same value twice, by asserting a serializer is called once per response. Test that serialization time for a representative payload stays within a budget, so a regression is caught.

# peak heap for a streamed response should not scale with the list size
node --expose-gc -e '
const before = process.memoryUsage().heapUsed;
await streamLargeList(100000);   // streamed
const after = process.memoryUsage().heapUsed;
console.log("peak delta MB=" + ((after-before)/1e6).toFixed(1));
'

Common pitfalls

Building the whole JSON string in memory for a large payload, stringifying then parsing then stringifying again, deep cloning with serialize-and-reparse when a clone suffices, adding a fast library without measuring a gain, and optimizing serialization when the real cost is the query or a downstream call are the recurring mistakes. Streaming, a single serialization at the boundary, a direct clone, measurement before a library, and profiling before optimizing address them.

Conclusion

JSON serialization is easy to over-spend on. Stream large payloads instead of buffering them whole, keep a value in one representation until the boundary, choose a schema-driven encoder only on a measured hot path, and measure size, time, and peak memory. Self-check by asserting peak memory does not scale with list size and that a value is serialized once per response. Then serialization stops being a hidden cost on the endpoints that matter.

Sources: MDN: JSON, Node.js: JSONStream and streaming encoders, RFC 8259: The JavaScript Object Notation (JSON) Data Interchange Format.

FAQ

When does JSON serialization become a bottleneck?
When the payload is large or the rate is high. A megabyte object serialized thousands of times a second costs real CPU and allocates a large string each time. Streaming and avoiding redundant conversions cut both the peak memory and the total work.
Is a faster JSON library worth it?
For a hot path serializing the same shape repeatedly, a compiled or schema-driven encoder can be several times faster. For occasional payloads, the platform encoder is fine and adds no dependency. Measure before adding a library.

Related Examples