# JSON5 vs JSON Performance: Benchmarks Measured | JSON5.dev


Source: https://json5.dev/compare/performance/

---

# JSON5 vs JSON: Performance, Measured

How much slower is JSON5 than JSON? We timed it on six kinds of document, in Node.js, Chromium and three Python libraries, and printed every script so you can check us.

The short answer is 17x to 100x slower to parse in JavaScript (3x to 28x to write) and about a thousand times slower in pure Python, depending on the shape of the data as much as its size. The longer answer is that almost none of it matters for a configuration file, and all of it matters for a hot path.

Below: medians and ranges, memory, cold-start cost, the reason the gap exists, a reconciliation with the figures published elsewhere on this site, and the three habits that make the whole question go away.

[The Numbers](#node-parse) [What to Do](#advice) [Scripts](#scripts)

![Two parsers racing through the same document on a workbench, with a stopwatch and timing cards for JSON and JSON5](https://json5.dev/img/hero/compare-performance.png)

**TL;DR:** On Node.js 24 the reference JSON5 parser took 0.28 ms for a 2.6 KB config (34x native `JSON.parse`) and 192 ms for 1.5 MB of records (25x). Nobody notices the first and everybody notices the second if it runs per request. Parse once, cache the result, and convert to JSON at build time for anything hot. The [comparison page](https://json5.dev/compare/) and the [Python guide](https://json5.dev/python/) use earlier runs of the same idea; the [reconciliation section](#reconcile) says how they differ.

[Method](#method) [Node Parse](#node-parse) [Node Stringify](#node-stringify) [Cold Start and Memory](#cold-memory) [Browser](#browser) [Python](#python) [Why](#why) [When It Matters](#when) [Advice](#advice) [Earlier Numbers](#reconcile) [Scripts](#scripts) [FAQ](#faq) [Sources](#references)

![Test icon](https://json5.dev/images/icons/test.png)

## How We Measured

Every figure on this page came from one machine on 11-29-2026: an Intel Core i9-9900 at 3.10 GHz running Windows 11, with nothing else deliberately running. The software was Node.js 24.22.1 (V8 13.6), the `json5` npm package at version 2.2.3, Chromium 143 driven by Playwright, and CPython 3.14.4 with `json5` 0.17.3, `pyjson5` 2.0.1 and `json-five` 1.1.2, each in its own virtual environment. The standard `json` module and the engine's native `JSON.parse` are the baselines.

Each benchmark warms the function up for 250 ms, then times single calls until it has at least 15 samples and 600 ms of work. The Python script warms up with one call (fifty for fast cases) and takes at least 15 samples over a second, or three samples if each run is slow. We report the **median** with the **minimum and maximum** in parentheses, because the median ignores the occasional garbage-collection pause and the range shows how noisy the machine was. The documents are built from a seeded random generator, so every run parses identical bytes, and each parser's output is checked against the input before any timing starts.

The six document shapes were chosen because they stress different parts of a parser:

-   **Small config:** about 2.6 KB, 20 routes and 15 flags, the file you read at startup.
-   **Records, ~100 KB and ~1.5 MB:** arrays of objects with strings, numbers, booleans, nested objects and `null`, the shape of an API response or a data export.
-   **Deep nesting:** 500 nested objects in Node.js, 100 in Python.
-   **Long strings:** a 2.2 MB pair of strings in Node.js (225 KB in Python), one full of escaped quotes and newlines.
-   **Numeric array:** 100,000 decimals in Node.js (20,000 in Python).

The inputs are strict JSON, the common [subset](https://json5.dev/glossary/#superset), so both parsers do the same job and the difference is the parser, not the syntax. Where a table says "indent 2" the same data was pretty-printed with two-space indentation, which adds bytes of whitespace the parser must skip. Python sizes are smaller than Node.js sizes only because the pure-Python parsers would otherwise need minutes per run.

![Node.js logo](https://json5.dev/images/tech/nodejs.png)

## Node.js: Parsing

Parse time in milliseconds, median with (minimum-maximum). The ratio is the JSON5 median divided by the native median.

Document

Bytes

JSON.parse

JSON5.parse

Ratio

Small config

2,656

0.008 (0.008-0.254)

0.283 (0.281-0.777)

34x

Records ~100 KB

100,124

0.511 (0.503-1.13)

12.6 (12.1-14.5)

25x

Records ~1.5 MB

1,514,121

7.69 (7.35-9.16)

191.9 (188.1-206.1)

25x

Deep nesting, 500 levels

6,900

0.069 (0.068-0.970)

1.15 (1.08-2.28)

17x

Long strings

2,250,022

1.75 (1.71-10.3)

173.5 (170.0-211.5)

99x

Numeric array, 100,000

1,077,565

3.63 (3.51-16.9)

119.8 (114.4-122.2)

33x

The same documents pretty-printed with two-space indentation:

Document (indent 2)

Bytes

JSON.parse

JSON5.parse

Ratio

Small config

3,848

0.009 (0.008-0.170)

0.354 (0.345-0.789)

40x

Records ~100 KB

160,725

0.542 (0.526-1.08)

16.3 (15.9-21.5)

30x

Records ~1.5 MB

2,413,022

8.48 (8.09-11.6)

244.7 (240.3-261.6)

29x

Deep nesting, 500 levels

761,905

0.288 (0.281-0.661)

39.8 (39.2-42.6)

138x

Long strings

2,250,031

1.78 (1.72-12.3)

172.2 (170.3-186.5)

97x

Numeric array, 100,000

1,377,566

3.71 (3.57-17.8)

142.0 (137.7-153.6)

38x

Three patterns stand out. First, **ordinary data sits at 25x to 40x**, from a 2.6 KB config up to 2.4 MB of records. In throughput terms the JSON5 parser handled about 8 MB per second on the 1.5 MB records and the native parser about 200 MB per second. Second, **long strings are the worst case at about 100x**: the reference parser appends to a string one character at a time, while native code copies the run in one step. Third, **whitespace is not free**. The 500-level nested document is 6.9 KB compact but 762 KB indented, and the indented version cost the JSON5 parser 40 ms against 0.29 ms for native code, a 138x gap, which fits a lexer that handles whitespace one character at a time (we did not profile it to confirm).

That last point has a practical edge: the ratio is not a constant of nature. A tightly packed file understates the gap and a lavishly indented one overstates it, which is one more reason to run [the script](#scripts) on your own files before deciding anything. Neither parser failed at 500 levels of nesting in Node.js; the reference parser's depth is bounded only by memory (we parsed a million levels of `{"k":` without an error, and so did native `JSON.parse`).

![Text format icon](https://json5.dev/images/icons/text-format.png)

## Node.js: Writing

Serializing is the other half. `JSON5.stringify` writes JSON5 (unquoted keys where legal, single-quoted strings, and [trailing commas](https://json5.dev/glossary/#trailing-comma) when indenting), while `JSON.stringify` writes strict JSON. Same method, same machine, same documents, in milliseconds.

Document

Indent

JSON.stringify

JSON5.stringify

Ratio

Small config

none

0.005 (0.004-3.03)

0.069 (0.067-0.287)

14x

Small config

2

0.006 (0.006-0.153)

0.072 (0.070-0.359)

12x

Records ~100 KB

none

0.263 (0.257-0.700)

2.89 (2.70-6.42)

11x

Records ~100 KB

2

0.381 (0.374-5.52)

2.96 (2.80-3.77)

8x

Records ~1.5 MB

none

4.71 (4.43-14.3)

44.4 (43.5-48.6)

9x

Records ~1.5 MB

2

6.63 (6.25-14.0)

47.2 (46.2-50.1)

7x

Deep nesting, 500 levels

none

0.067 (0.065-0.481)

0.237 (0.225-1.13)

4x

Deep nesting, 500 levels

2

1.48 (1.42-10.7)

72.6 (61.4-77.6)

49x

Long strings

none

2.68 (2.50-14.2)

74.9 (56.4-78.7)

28x

Numeric array, 100,000

none

7.34 (7.04-8.53)

20.0 (19.7-35.7)

2.7x

Numeric array, 100,000

2

7.87 (7.63-9.17)

20.6 (20.0-37.0)

2.6x

Writing is the smaller problem: **3x to 28x** on most shapes, against 17x to 100x for reading. Numbers are the exception in the good direction, because both functions spend most of their time converting a double to text and the gap shrinks to under 3x. The deep indented case is the exception in the bad direction. Reading the 2.2.3 source explains it: before serializing each object or array, `JSON5.stringify` checks the stack of parents with `indexOf` to detect cycles, so the cost of that check grows with depth, and so does the indentation written on every line, so the work grows faster than the data. Nothing that real configuration or data produces is 500 levels deep, but it shows how a benchmark can find a cliff.

![Time icon](https://json5.dev/images/icons/time.png)

## Cold Start and Memory

The tables above are steady-state numbers, measured after the engine has compiled and optimized the code. A configuration file is not steady-state: it is read once, by a process that has just started. We measured that case separately by launching a fresh Node.js process 15 times and timing three things on a 1,646-byte config (script in the [scripts section](#scripts)).

Step in a fresh process

Median

Range

First `JSON.parse`

0.019 ms

0.018-0.021 ms

`require('json5')`

3.89 ms

3.81-4.21 ms

First `JSON5.parse`

1.54 ms

1.46-1.69 ms

The honest startup cost of JSON5 in Node.js is therefore about **5.4 ms**, about 70 percent of it loading the library and the rest the first, unoptimized parse. That first parse alone takes about five times the steady-state time for a similar file, and the whole 5.4 ms is about 280 times the native first call. It is still a rounding error next to starting the runtime itself, but it is the number to quote for a command-line tool that runs thousands of times, not 0.28 ms.

**Memory** is measurable too, with a caveat about method. We parsed the 8,900-record document in a fresh process, forced garbage collection twice before and after, and read V8's used-heap figure. Native `JSON.parse` left **2.65 MB** of live heap and `JSON5.parse` left **7.10 MB**, about 2.7 times as much, identical across three runs. The two trees hold the same data; we did not investigate why one is bigger. The input text is held in both runs and is not counted in the difference. A first attempt that measured `process.memoryUsage()` inside the benchmark loop reported zero for the JSON5 case, because the optimizer discarded the unused result, so treat any in-loop memory figure with suspicion.

![Chrome logo](https://json5.dev/images/tech/chrome.png)

## In the Browser

A page that ships a JSON5 parser pays twice: once to download and compile the bundle, once per document parsed. We measured both in Chromium 143 (headless, through Playwright) using the minified UMD bundle from the 2.2.3 package, which is 31,631 bytes raw and about 9.5 KB gzipped. The browser clock is coarse (we saw 0.1 ms steps), so each sample for the small document is the mean of 1,000 parses.

Document

Bytes

JSON.parse

JSON5.parse

Ratio

Small config

1,337

0.004 ms

0.139 ms (0.135-0.145)

35x

Records ~100 KB

100,124

0.365 ms (0.350-0.445)

10.98 ms (10.75-12.03)

30x

Records ~1.5 MB

1,514,121

6.0 ms (5.7-6.8)

164.6 ms (162.1-175.3)

27x

The ratios match Node.js, which is expected: Chromium and Node.js both run V8, so the engine, the parser source and the gap are the same. The extra cost in a browser is the first load. In 15 fresh pages, compiling and running the bundle and parsing one small config took a median of **2.5 ms** (2.3-2.7 ms). That excludes the network transfer of roughly 9.5 KB, which on a slow mobile connection will cost far more than the compile. A re-run on Chromium 159 was faster (the 1.5 MB records took 129 ms for JSON5 and 5.3 ms for native, a 24x ratio), so absolute browser times move with the Chromium version and the ratio moves less. The practical reading: a one-off parse of a small document in the browser is invisible, a 1.5 MB document costs a visible 165 ms of main-thread time, and a site that only needs strict JSON should not ship the bundle at all.

![Python logo](https://json5.dev/images/tech/python.png)

## Python: Three Libraries

Python has no built-in JSON5 support, so the comparison is between the standard `json` module and three packages from the [Python guide](https://json5.dev/python/): `json5` (pure Python), `pyjson5` (compiled) and `json-five` (pure Python, comment-preserving). `json5` and `json-five` both install a module called `json5`, so each ran in its own virtual environment. Parse medians in milliseconds, with the range in parentheses:

Document

Bytes

json

pyjson5

json5

json-five

Small config

2,910

0.018 (0.017-0.844)

0.023 (0.022-0.125)

21.1 (20.5-22.7)

16.5 (16.0-17.8)

Records ~100 KB

112,777

0.918 (0.885-1.63)

1.15 (1.14-2.05)

914 (903-956)

892 (875-941)

Records ~1.5 MB

1,701,133

14.6 (13.6-20.1)

19.8 (18.1-25.8)

13,776 (13,666-13,803)

13,583 (13,482-13,600)

Deep nesting, 100 levels

1,601

0.020 (0.019-0.117)

Error: nesting limit

Error: RecursionError

20.5 (19.9-23.7)

Long strings

225,025

0.287 (0.283-0.589)

0.958 (0.926-1.89)

1,213 (1,193-1,240)

27.9 (27.1-30.9)

Numeric array, 20,000

235,512

2.44 (2.32-4.14)

1.84 (1.79-3.21)

1,655 (1,630-1,738)

866 (857-889)

And writing, using each library's `dumps` or `encode`:

Document

json

pyjson5

json5

json-five

Small config

0.019

0.020

0.419

0.471

Records ~100 KB

0.953

1.03

18.8

24.8

Records ~1.5 MB

15.5

16.4

291.9

371.5

Deep nesting, 100 levels

0.028

0.043

0.349

0.684

Long strings

0.431

0.218

22.6

0.455

Numeric array, 20,000

6.00

1.01

18.9

37.5

The ladder is steeper than in JavaScript. On ordinary records the pure-Python parsers took about 930x to 1,000x the standard library's time (1,170x on the small config): 914 ms against 0.92 ms for 113 KB, and a full **13.8 seconds** for 1.7 MB, roughly 0.12 MB per second. The compiled `pyjson5` stayed within 1.25x to 1.4x of `json` on records and 3.3x on the long-string document, and was actually faster than `json` on the numeric array (1.84 ms against 2.44 ms). Its writer was faster than `json.dumps` on strings and numbers, but remember it emits JSON-shaped output with quoted keys and no trailing commas, so it is not writing JSON5 in the style the pure-Python writers do.

Shape matters more than size between the two pure-Python parsers. On records they were within 3 percent of each other, but on the long-string document `json-five` was 43 times faster than `json5`, and on the numeric array 1.9 times. The deep-nesting row shows a different kind of difference, correctness under limits. In a binary search with a Python recursion limit of 1,000 (the default), `json5` parsed objects nested up to 43 levels and raised `RecursionError` beyond that, `pyjson5` stopped at 32 by design (its documentation names a `maxdepth` parameter that defaults to a global limit, and a negative value lifts it up to Python's own recursion limit), and `json-five` reached 495. The standard library handled 5,000 levels without complaint.

![Question icon](https://json5.dev/images/icons/question.png)

## Why JSON.parse Is Faster

Two things compound. The first is **where the code runs**. `JSON.parse` is part of the engine: library code has to be loaded, compiled and warmed up first, and the built-in is not subject to the cold-start costs shown above. The reference JSON5 parser is ordinary JavaScript. The V8 team's own account of why `JSON.parse` beats a JavaScript object literal credits a simpler grammar: JSON, they write, "can be parsed more efficiently than JavaScript." The same logic applies one step down, between JSON and a larger superset.

The second is **what the grammar demands**. JSON has a handful of [token](https://json5.dev/glossary/#punctuator) types, strings with a short escape list, and numbers in one form. JSON5 adds comments, single and double quotes, [line continuations](https://json5.dev/glossary/#line-continuation), hexadecimal numbers, `Infinity` and `NaN`, and keys that may be unquoted ECMAScript 5 identifiers, which can contain Unicode letters and `\uXXXX` escapes. A parser that supports all of that cannot take the shortcuts a JSON-only parser can. It needs a general lexer.

The 2.2.3 source shows what that costs in practice. The lexer is a state machine in which every step calls `peek()`, which creates a one-character string with `String.fromCodePoint(source.codePointAt(pos))`; `read()` then updates the line and column counters; string contents are assembled with `buffer += read()` per character; and the character-class helpers (`isDigit`, `isHexDigit`, the identifier tests) are built on regular expressions. That design is correct and compact, which is why the whole package is under 32 KB minified, and it is why a long string costs about 100x: every one of its characters goes through that path, where native code copies the run. Our measured throughput of 8 to 13 MB per second is what a character-at-a-time JavaScript lexer looks like.

The main branch on GitHub is not identical to the 2.2.3 release (its lexer helper is named differently), so a future release may behave differently. We measured only the 2.2.3 release that ships on npm today. For the grammar behind the extra work, see the [grammar page](https://json5.dev/spec/grammar/) and the [design rationale](https://json5.dev/design-rationale/).

![Target icon](https://json5.dev/images/icons/target.png)

## When It Matters and When It Does Not

A ratio is not a cost. A 34x slowdown on 0.008 ms is 0.28 ms; the same ratio on a hot path is a service that falls over. Use this rough map, with the figures above as the yardstick.

Situation

How often it parses

Verdict

Application config, read at startup

Once per process

Irrelevant: about 5 ms including the library load, in Node.js. About 20 ms in pure Python.

Command-line tool, many short runs

Once per invocation

Measure: the 5 ms library load is paid every time.

Config re-read on file change

Rarely

Fine with an mtime cache.

Per-request parse of a 100 KB document

Hundreds per second

Problem: 12.6 ms of CPU each. Convert to JSON.

Bulk data or logs, MB and up

Continuously

Wrong format. Use JSON, or JSON Lines for streams (see [the JSONL comparison](https://json5.dev/compare/jsonl/), [JSONL.rest, our sister reference site for JSON Lines](https://jsonl.rest/), and [NDJSON.com, our sister reference site for NDJSON](https://ndjson.com/)); this is machine data.

Browser page, small document

Once per page

Fine, but the 9.5 KB bundle and 2.5 ms compile are avoidable.

Pure Python, any file over a few KB in a loop

Per call

Use `pyjson5` or convert to JSON.

The dividing question is the one the [comparison page](https://json5.dev/compare/) asks about authorship: if a person writes the file, it is read rarely, and the format earns its keep; if a program writes it, or it is read per request, the format is the wrong tool and the benchmark is the evidence.

![Idea icon](https://json5.dev/images/icons/idea.png)

## What to Do About It

### 1\. Parse once

Read the file when the process starts and hand the object around. The most common performance mistake is parsing inside a request handler.

### 2\. Cache by modification time

If the file can change while the program runs, re-parse only when its modification time moves. This tested loader parsed the file once across four calls:

`// load-config.js - parse once, re-parse only when the file changes const fs = require('node:fs'); const JSON5 = require('json5'); let cached = { mtimeMs: 0, value: null }; function loadConfig(file) { const mtimeMs = fs.statSync(file).mtimeMs; if (mtimeMs !== cached.mtimeMs) { cached = { mtimeMs, value: JSON5.parse(fs.readFileSync(file, 'utf8')) }; console.log('parsed', file); } return cached.value; } for (let i = 0; i < 3; i++) loadConfig('config.json5'); console.log(loadConfig('config.json5'));`

### 3\. Convert to JSON at build time

Keep the comments and trailing commas in the source file people edit, and ship strict JSON to whatever reads it at runtime. The runtime then uses `JSON.parse` and never loads the library at all. This script, run as a build step, turned a JSON5 file into an 83-byte JSON file:

`// build-config.js - run in the build, ship config.json const fs = require('node:fs'); const JSON5 = require('json5'); const data = JSON5.parse(fs.readFileSync('config.json5', 'utf8')); fs.writeFileSync('config.json', JSON.stringify(data) + '\n'); console.log('wrote config.json,', fs.statSync('config.json').size, 'bytes');`

Run against a file with two comments, single-quoted strings and trailing commas, it printed `wrote config.json, 83 bytes` and produced `{"host":"0.0.0.0","port":8080,"retries":3,"features":{"search":true,"beta":false}}`. The [performance tutorial](https://json5.dev/tutorials/performance/), the [conversion tools](https://json5.dev/tools/conversion/) and the [migration guide](https://json5.dev/tutorials/migration-from-json/) cover the same step from other angles. What is lost on the way is the comments, which is the point: they were for humans.

### 4\. Choose the right tool for the language

In Python use `pyjson5` for anything bigger than a small config, as the [Python guide](https://json5.dev/python/) recommends. In JavaScript, the reference parser is the only widely used full-featured choice, so conversion is the lever. For files too big to hold in memory, see [streaming and large files](https://json5.dev/tutorials/streaming-parsing/).

### 5\. Measure your own files

The ratio moves by a factor of six with the shape and by as much as eight with whitespace. If a number matters to a decision, run the script below on a sample of your real data.

![Compare icon](https://json5.dev/images/icons/compare.png)

## How This Differs From the Earlier Numbers

The [comparison page](https://json5.dev/compare/) and the [Python guide](https://json5.dev/python/) each carry a benchmark we ran on the same workstation between 11-25-2026 and 11-29-2026. They differ from this page in places, and you should know where.

Measurement

Earlier page

This page

Node.js, small config, ratio

38x (0.02 ms vs 0.71 ms, 2.8 KB)

34x (0.008 ms vs 0.283 ms, 2.7 KB)

Node.js, 100-142 KB records, ratio

45x (0.83 ms vs 37.7 ms, 142 KB)

25x (0.511 ms vs 12.6 ms, 100 KB); 30x indented, 161 KB

Node.js, 1.4-1.5 MB records, ratio

33x (10.2 ms vs 336 ms, 1.4 MB)

25x (7.69 ms vs 191.9 ms, 1.5 MB); 29x indented, 2.4 MB

Python `json5`, small config

40 ms (2.8 KB)

21.1 ms (2.9 KB)

Python `json5`, 113-142 KB data

1,841 ms (142 KB)

914 ms (113 KB)

Python `pyjson5` vs `json5`

about 550x to 700x faster

about 700x to 900x on config and records

Python `pyjson5` vs `json`

1.4x to 1.6x

1.25x to 1.4x on records

Python pure parsers vs each other

"within about 10 percent"

3 percent on records, up to 43x on long strings

**The orders of magnitude agree.** JavaScript is a few tens of times slower, pure Python is about a thousand times slower, the compiled Python parser is about as fast as the standard library, and a config file takes milliseconds either way. **The details do not.** In Node.js the earlier runs gave higher ratios (33x to 45x) than the same shapes do here (25x to 34x compact, 29x to 40x indented), and the earlier absolute times were up to twice ours. Both parsers got faster between runs, so the likeliest causes are a different set of documents (the earlier 142 KB file averaged roughly 355 bytes per record against about 167 here), different machine load, and different warm-up and run counts. We cannot separate those after the fact, and we have not rerun the earlier inputs. The Python figures moved the same way: the earlier run reported 40 ms for a 2.8 KB config where this one reports 21 ms, and the "within about 10 percent" claim about the two pure-Python parsers holds for records but not for strings or numbers.

How to read the three pages together: quote ranges, not points. "Roughly 25x to 40x slower on ordinary data in Node.js, up to 100x on long strings; about 1,000x slower in pure Python" is supported by every run we have. A single "38x" is a measurement of one file on one afternoon.

![Code icon](https://json5.dev/images/icons/code.png)

## Reproduce It: The Full Scripts

Everything above came from these scripts, unedited apart from comments. Put each in an empty folder, install the packages named in its header and run it. Your numbers will differ; the shape of the results should not.

### Node.js: parse and stringify (bench.js)

Needs a current Node.js (we used 24.22.1). It exits with an error if either parser disagrees with the input, so a green run means the timings are for correct output.

``// bench.js - parse and stringify benchmark: native JSON vs the json5 package. // Run: npm install --save-exact json5 (this page used 2.2.3) && node bench.js 'use strict'; const JSON5 = require('json5'); const { performance } = require('node:perf_hooks'); // ---- deterministic data (seeded PRNG so every run builds the same documents) let seed = 12345; const rnd = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296); function makeConfig() { const c = { name: 'api-gateway', version: '3.4.1', server: { host: '0.0.0.0', port: 8080, tls: { enabled: true, cert: '/etc/ssl/cert.pem', key: '/etc/ssl/key.pem' } }, routes: [], features: {}, limits: { rps: 500, burst: 1000, timeoutMs: 30000 } }; for (let i = 0; i < 20; i++) c.routes.push({ path: '/api/v1/resource' + i, method: ['GET', 'POST'][i % 2], upstream: 'http://svc' + i + '.internal:' + (9000 + i), retries: 3, cache: i % 3 === 0 }); for (let i = 0; i < 15; i++) c.features['flag_' + i] = i % 2 === 0; return c; } function makeRecords(n) { const out = []; for (let i = 0; i < n; i++) out.push({ id: i, name: 'user' + i, login: 'user' + i + '.example.com', active: rnd() > 0.5, score: Math.round(rnd() * 1e6) / 100, tags: ['a' + (i % 7), 'b' + (i % 11), 'c' + (i % 13)], address: { city: 'City ' + (i % 97), zip: String(10000 + (i % 89999)) }, note: null }); return out; } function makeDeep(depth) { let o = { leaf: 1 }; for (let i = 0; i < depth; i++) o = { k: o, n: i }; return o; } const makeLongStrings = () => ({ text: 'The quick brown fox "jumps" over\nthe lazy dog. '.repeat(25000), plain: 'abcdefghij'.repeat(100000) }); const makeNumbers = (n) => Array.from({ length: n }, () => Math.round(rnd() * 1e9) / 1e4); const docs = [ ['small config', makeConfig()], ['records ~100 KB', makeRecords(600)], ['records ~1.5 MB', makeRecords(8900)], ['deep nesting (depth 500)', makeDeep(500)], ['long strings (2.2 MB)', makeLongStrings()], ['numeric array (100,000)', makeNumbers(100000)], ]; // ---- timing: warm up, then at least MIN_RUNS runs and MIN_MS of total time const MIN_RUNS = 15, MIN_MS = 600, WARMUP_MS = 250; function bench(fn) { let t = performance.now(); while (performance.now() - t < WARMUP_MS) fn(); const times = []; const start = performance.now(); while (times.length < MIN_RUNS || performance.now() - start < MIN_MS) { const a = performance.now(); fn(); times.push(performance.now() - a); if (times.length >= 200000) break; } times.sort((x, y) => x - y); return { median: times[times.length >> 1], min: times[0], max: times[times.length - 1], runs: times.length }; } const fmt = (ms) => ms >= 10 ? ms.toFixed(1) : ms >= 1 ? ms.toFixed(2) : ms.toFixed(3); console.log('node', process.version, '| json5', require('json5/package.json').version, '| V8', process.versions.v8); console.log('| document | bytes | op | native median (min-max) ms | json5 median (min-max) ms | ratio |'); for (const [label, value] of docs) { const text = JSON.stringify(value); const pretty = JSON.stringify(value, null, 2); const bytes = Buffer.byteLength(text), prettyBytes = Buffer.byteLength(pretty); // sanity: both parsers must agree if (JSON.stringify(JSON5.parse(text)) !== text) throw new Error('mismatch on ' + label); const rows = [ ['parse', () => JSON.parse(text), () => JSON5.parse(text)], ['parse (indent 2)', () => JSON.parse(pretty), () => JSON5.parse(pretty)], ['stringify', () => JSON.stringify(value), () => JSON5.stringify(value)], ['stringify (indent 2)', () => JSON.stringify(value, null, 2), () => JSON5.stringify(value, null, 2)], ]; for (const [op, a, b] of rows) { const ra = bench(a), rb = bench(b); console.log(`| ${label} | ${op === 'parse (indent 2)' || op === 'stringify (indent 2)' ? prettyBytes : bytes} | ${op} | ${fmt(ra.median)} (${fmt(ra.min)}-${fmt(ra.max)}) | ${fmt(rb.median)} (${fmt(rb.min)}-${fmt(rb.max)}) | ${(rb.median / ra.median).toFixed(1)}x | runs ${ra.runs}/${rb.runs}`); } }``

### Node.js: memory (mem.js)

Run it as `node --expose-gc mem.js native` and `node --expose-gc mem.js json5`, each in its own process.

`const v8=require('node:v8'), JSON5=require('json5'); const which=process.argv[2]; const recs=[];for(let i=0;i<8900;i++)recs.push({id:i,name:'user'+i,login:'user'+i+'.example.com',active:i%2===0,score:i*1.37,tags:['a'+i%7,'b'+i%11,'c'+i%13],address:{city:'City '+i%97,zip:String(10000+i)},note:null}); const text=JSON.stringify(recs); recs.length=0; global.gc();global.gc(); const used=()=>v8.getHeapStatistics().used_heap_size; const b=used(); global.keep=(which==='native'?JSON.parse:JSON5.parse)(text); global.gc();global.gc(); console.log(which,((used()-b)/1048576).toFixed(2),'MB', global.keep.length);`

### Node.js: cold start (startup.js)

Run it about 15 times in a loop and take the median of each field; every run is a new process.

`// startup.js - what a one-off config read costs in a fresh process (run it several times) const { performance } = require('node:perf_hooks'); const text = JSON.stringify({ name: 'api-gateway', routes: Array.from({ length: 20 }, (_, i) => ({ path: '/r' + i, upstream: 'http://svc' + i + '.internal:' + (9000 + i), retries: 3, cache: i % 3 === 0 })) }); let t = performance.now(); JSON.parse(text); const native = performance.now() - t; t = performance.now(); const JSON5 = require('json5'); const load = performance.now() - t; t = performance.now(); JSON5.parse(text); const first = performance.now() - t; console.log(JSON.stringify({ bytes: text.length, nativeFirstParseMs: +native.toFixed(3), requireJson5Ms: +load.toFixed(2), json5FirstParseMs: +first.toFixed(2) }));`

### Chromium (browser.js)

Needs `playwright` and a downloaded Chromium. It reads the minified bundle from the installed package and runs the timings inside the page.

``// browser.js - the same comparison inside Chromium, plus the cost of loading the bundle. // Run: npm install --save-exact json5 (this page used 2.2.3) playwright && npx playwright install chromium && node browser.js 'use strict'; const fs = require('node:fs'); const path = require('node:path'); const { chromium } = require('playwright'); const bundle = fs.readFileSync(path.join(require.resolve('json5/package.json'), '..', 'dist', 'index.min.js'), 'utf8'); let seed = 12345; const rnd = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296); const records = (n) => Array.from({ length: n }, (_, i) => ({ id: i, name: 'user' + i, login: 'user' + i + '.example.com', active: rnd() > 0.5, score: Math.round(rnd() * 1e6) / 100, tags: ['a' + (i % 7), 'b' + (i % 11), 'c' + (i % 13)], address: { city: 'City ' + (i % 97), zip: String(10000 + (i % 89999)) }, note: null })); const texts = { 'records ~100 KB': JSON.stringify(records(600)), 'records ~1.5 MB': JSON.stringify(records(8900)) }; texts['small config'] = JSON.stringify({ name: 'api-gateway', routes: records(18).map((r) => ({ path: '/r' + r.id, upstream: r.login, retries: 3, cache: r.active })) }); (async () => { const browser = await chromium.launch(); console.log('Chromium', browser.version(), '| bundle bytes', Buffer.byteLength(bundle)); const page = await browser.newPage(); await page.goto('about:blank'); const out = await page.evaluate(({ bundle, texts }) => { const med = (a) => a.sort((x, y) => x - y)[a.length >> 1]; const res = { load: [], first: [], steady: {} }; // cost of compiling and running the bundle, 21 times in fresh function scopes for (let i = 0; i < 21; i++) { const t = performance.now(); new Function(bundle + '\nreturn JSON5;')(); res.load.push(performance.now() - t); } const J = new Function(bundle + '\nreturn JSON5;')(); const small = texts['small config']; const t1 = performance.now(); J.parse(small); res.first.push(performance.now() - t1); for (const [label, text] of Object.entries(texts)) { // the browser clock is coarse (0.1 ms), so each sample is a batch of `reps` parses divided by reps const reps = text.length < 5e3 ? 1000 : text.length < 2e5 ? 20 : 1; const run = (fn, n) => { for (let i = 0; i < 20; i++) fn(); const a = []; for (let i = 0; i < n; i++) { const t = performance.now(); for (let r = 0; r < reps; r++) fn(); a.push((performance.now() - t) / reps); } return a; }; const n = text.length > 1e6 ? 15 : text.length > 5e4 ? 40 : 30; const a = run(() => JSON.parse(text), n), b = run(() => J.parse(text), n); res.steady[label] = { bytes: text.length, native: [med(a.slice()), Math.min(...a), Math.max(...a)], json5: [med(b.slice()), Math.min(...b), Math.max(...b)], runs: n }; } return { load: { median: med(res.load.slice()), min: Math.min(...res.load), max: Math.max(...res.load) }, first: res.first[0], steady: res.steady }; }, { bundle, texts }); console.log(JSON.stringify(out, null, 1)); // cold cost: a fresh page each time, compile the bundle and parse the small config once const cold = []; for (let i = 0; i < 15; i++) { const p = await browser.newPage(); cold.push(await p.evaluate(({ bundle, small }) => { const t = performance.now(); const J = new Function(bundle + '\nreturn JSON5;')(); J.parse(small); return performance.now() - t; }, { bundle, small: texts['small config'] })); await p.close(); } cold.sort((a, b) => a - b); console.log('cold load + first parse of small config, ms: median', cold[7], 'min', cold[0], 'max', cold[14]); await browser.close(); })();``

### Python (bench.py)

The comment block at the top shows the one-environment-per-package setup. On Windows replace `v1/bin/` with `v1\Scripts\`.

`# bench.py - parse and dump benchmark: json (standard library) vs json5, pyjson5, json-five. # One virtual environment per package (json5 and json-five both install a module named "json5"): # python -m venv v1 && v1/bin/pip install json5 && v1/bin/python bench.py json5 # python -m venv v2 && v2/bin/pip install pyjson5 && v2/bin/python bench.py pyjson5 # python -m venv v3 && v3/bin/pip install json-five && v3/bin/python bench.py json-five # python bench.py json import json, random, statistics, sys, time from importlib import metadata lib = sys.argv[1] if lib == "json": parse, dump, version = json.loads, lambda v: json.dumps(v), sys.version.split()[0] elif lib == "json5": import json5 parse, dump, version = json5.loads, lambda v: json5.dumps(v), metadata.version("json5") elif lib == "pyjson5": import pyjson5 parse, dump, version = pyjson5.decode, lambda v: pyjson5.encode(v), metadata.version("pyjson5") elif lib == "json-five": import json5 as jf # json-five installs its module under the name json5 parse, dump, version = jf.loads, lambda v: jf.dumps(v), metadata.version("json-five") else: raise SystemExit("unknown library " + lib) rng = random.Random(12345) def records(n): return [{"id": i, "name": f"user{i}", "login": f"user{i}.example.com", "active": rng.random() > 0.5, "score": round(rng.random() * 1e4, 2), "tags": [f"a{i % 7}", f"b{i % 11}", f"c{i % 13}"], "address": {"city": f"City {i % 97}", "zip": str(10000 + i % 89999)}, "note": None} for i in range(n)] def config(): return {"name": "api-gateway", "version": "3.4.1", "server": {"host": "0.0.0.0", "port": 8080, "tls": {"enabled": True, "cert": "/etc/ssl/cert.pem", "key": "/etc/ssl/key.pem"} }, "routes": [{"path": f"/api/v1/resource{i}", "method": ["GET", "POST"][i % 2], "upstream": f"http://svc{i}.internal:{9000 + i}", "retries": 3, "cache": i % 3 == 0} for i in range(20)], "features": {f"flag_{i}": i % 2 == 0 for i in range(15)}, "limits": {"rps": 500, "burst": 1000, "timeoutMs": 30000} } def deep(depth): o = {"leaf": 1} for i in range(depth): o = {"k": o, "n": i} return o docs = [ ("small config", config()), ("records ~100 KB", records(600)), ("records ~1.5 MB", records(8900)), ("deep nesting (depth 100)", deep(100)), ("long strings (225 KB)", {"text": 'The quick brown fox "jumps" over\nthe lazy dog. ' * 2500, "plain": "abcdefghij" * 10000}), ("numeric array (20,000)", [round(rng.random() * 1e5, 4) for _ in range(20000)]), ] def bench(fn): fn() # warmup (a second one for fast cases) if True: t = time.perf_counter(); fn(); one = time.perf_counter() - t if one < 0.05: for _ in range(50): fn() times, start = [], time.perf_counter() while True: t = time.perf_counter(); fn(); times.append((time.perf_counter() - t) * 1000) el = time.perf_counter() - start if (len(times) >= 15 and el >= 1.0) or (len(times) >= 3 and el >= 20) or len(times) >= 100000: break times.sort() return statistics.median(times), times[0], times[-1], len(times) def fmt(ms): return f"{ms:.1f}" if ms >= 10 else f"{ms:.2f}" if ms >= 1 else f"{ms:.3f}" print(f"# {lib} {version} | Python {sys.version.split()[0]}") for label, value in docs: text = json.dumps(value) try: if json.dumps(parse(text)) != text: print(f"| {label} | MISMATCH"); continue med, lo, hi, n = bench(lambda: parse(text)) print(f"| {label} | {len(text.encode())} | parse | {fmt(med)} ({fmt(lo)}-{fmt(hi)}) | runs {n}") except Exception as e: print(f"| {label} | parse FAILED {type(e).__name__}: {str(e)[:60]}") try: med, lo, hi, n = bench(lambda: dump(value)) print(f"| {label} | {len(text.encode())} | dump | {fmt(med)} ({fmt(lo)}-{fmt(hi)}) | runs {n}") except Exception as e: print(f"| {label} | dump FAILED {type(e).__name__}: {str(e)[:60]}")`

### Python: nesting limit (depth.py)

Finds the deepest object nesting each library accepts under the default recursion limit. Run it as `python depth.py json5 600` (the second argument is an upper bound for the search).

`import sys, json lib = sys.argv[1] if lib == "pyjson5": import pyjson5; f = pyjson5.decode elif lib == "json5": import json5; f = json5.loads else: import json5; f = json5.loads def ok(d): t = '{"k":' * d + '1' + '}' * d try: f(t); return True except BaseException: return False lo, hi = 1, int(sys.argv[2]) while lo < hi - 1: m = (lo + hi) // 2 if ok(m): lo = m else: hi = m print(lib, "max object depth:", lo)`

## Performance: Common Questions

### How much slower is JSON5 than JSON?

In Node.js, 17x to 40x to parse ordinary data and up to about 100x for long strings; 3x to 28x to write. In pure Python, roughly 1,000x to parse. With the compiled `pyjson5`, 1.25x to 3.3x.

### Does it matter for a config file?

No. A 2.6 KB config costs 0.28 ms once the library is loaded and about 5.4 ms in a fresh Node.js process. Pure Python takes about 20 ms. Do it once at startup and move on.

### Is the JSON5 parser slow because the format is complex?

Partly. The extra syntax forces a general lexer, but the larger factor is that the parser is JavaScript while `JSON.parse` is built into the engine. The compiled Python parser shows that a JSON5 parser can come within a small factor of the standard library.

### Does a newer Node.js make it faster?

Probably a little for both parsers, and the ratio is unlikely to change much, but we have not measured other versions. Our figures are for Node.js 24.22.1 and V8 13.6 only. The script is there for the check.

### Should I minify my JSON5 files?

If you must parse them at runtime, yes: indentation cost about 25 to 30 percent more parse time on records and far more on pathological nesting. Better still, convert to JSON at build time and read that. See the [online minifier](https://json5.dev/tools/online-minifier/).

### Why did your earlier numbers differ?

Different documents and a different run. The [reconciliation table](#reconcile) lists each pair and the likely reasons. The orders of magnitude agree.

## Related Pages

[![Speed icon](https://json5.dev/images/icons/speed.png)

### Performance Tutorial

Caching, build-time conversion and profiling

](https://json5.dev/tutorials/performance/)[![Compare icon](https://json5.dev/images/icons/compare.png)

### JSON5 vs JSON

Syntax, features and when to use each

](https://json5.dev/compare/)[![Python logo](https://json5.dev/images/tech/python.png)

### JSON5 for Python

Choosing between three libraries

](https://json5.dev/python/)[![JavaScript logo](https://json5.dev/images/tech/javascript.png)

### JSON5 for JavaScript

The reference parser and its bundles

](https://json5.dev/javascript/)[![Stream icon](https://json5.dev/images/icons/stream.png)

### Streaming and Large Files

When the document will not fit in memory

](https://json5.dev/tutorials/streaming-parsing/)[![Convert icon](https://json5.dev/images/icons/convert.png)

### Conversion Tools

Turn JSON5 into JSON for production

](https://json5.dev/tools/conversion/)

## Sources

(10)

1.  [V8 blog: The cost of JavaScript in 2019](https://v8.dev/blog/cost-of-javascript-2019) (JSON.parse versus object literals and the simpler JSON grammar)
2.  [json5/json5 on GitHub](https://github.com/json5/json5), the reference implementation; `lib/parse.js` and `lib/stringify.js` from the 2.2.3 package were read for the lexer and serializer behavior described above
3.  [npm: json5](https://www.npmjs.com/package/json5) (version 2.2.3, `dist/index.min.js` at 31,631 bytes)
4.  [PyPI: json5 0.17.3](https://pypi.org/project/json5/), the pure-Python package benchmarked
5.  [PyPI: pyjson5 2.0.1](https://pypi.org/project/pyjson5/) and its [repository](https://github.com/Kijewski/pyjson5) (the `decode` documentation for `maxdepth` was read from the installed package)
6.  [PyPI: json-five 1.1.2](https://pypi.org/project/json-five/)
7.  [Node.js documentation: perf\_hooks](https://nodejs.org/api/perf_hooks.html), the timer used by the Node.js scripts
8.  [Playwright documentation](https://playwright.dev/docs/intro), used to drive Chromium for the browser measurements
9.  [JSONL.rest, our sister reference site for JSON Lines](https://jsonl.rest/), and [NDJSON.com, our sister reference site for NDJSON](https://ndjson.com/)
10.  [The JSON5 specification](https://json5.org/)

Last reviewed: November 29, 2026.
