Skip to content

Speed up copy.deepcopy() of containers holding atomic elements #150815

Description

@gaborbernat

copy.deepcopy() copies a structure by sending every element back through deepcopy(). For elements that need no copying at all — strings, ints, None, booleans, floats and the other immutable atomic types — that round trip still costs a function call each, even though the value handed back is the same object.

Real data is dominated by these atomic leaves. A parsed JSON document, a settings dict cloned before mutation, a record copied inside a framework: the keys are strings and most values are strings and numbers. Copying such a structure spends most of its time calling deepcopy() only to receive the same object straight back.

Deep-copying 105 JSON documents drawn from the top-1000 PyPI projects takes 1.20 ms today. Folding the atomic-type check into the dict, list and tuple copiers brings that to 970 µs, 23% faster, with identical handling of shared references, recursive structures and int/tuple subclasses.

Linked PRs

Activity

  1. added 2 commits that reference this issue on Jun 2, 2026
  2. added
    type-featureA feature request or enhancement
    performancePerformance or resource usage
    stdlibStandard Library Python modules in the Lib/ directory
    on Jun 3, 2026
  3. added a commit that references this issue on Jun 3, 2026
  4. gaborbernat commented on Sep 23, 2026

    @gaborbernat
    ContributorAuthor

    Closing: the change in #150822 was judged too much complexity for the gain (#150822 (comment)). A C implementation of deepcopy would be the route for larger speedups.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    performancePerformance or resource usagestdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions