Skip to content

json.JSONEncoder.iterencode creates reference cycles #141686

Closed

Description

@brandtbucher

json.JSONEncoder.iterencode (and, by extension, json.dump) creates reference cycles on every call where _one_shot is False (the default). This is because it defines three mutually-recursive nested functions, which keep each other alive through their closures.

According to local microbenchmarks adapted from pyperformance, clearing these cycles explicitly results in a ~10% slowdown for json.dump when the GC is disabled, but a ~20% speedup when the GC is enabled (since we're now eagerly doing the work done less efficiently by the GC).

I'll have a patch up soon.

Linked PRs

Activity

  1. self-assigned this
    on Nov 18, 2025
  2. added
    performancePerformance or resource usage
    stdlibStandard Library Python modules in the Lib/ directory
    on Nov 18, 2025
  3. added a commit that references this issue on Nov 18, 2025
  4. added a commit that references this issue on Nov 18, 2025
  5. added a commit that references this issue on Dec 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

performancePerformance or resource usagestdlibStandard Library Python modules in the Lib/ directory

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions