Skip to content

new_subdoc() is slow for in-memory documents #201

Done

Description

@cvas22

The problem

Inserting a python-docx Document or a rendered DocxTemplate with new_subdoc() costs about 23ms per subdoc, more than loading one from a stream. With a sub-template rendered in a loop that adds up fast, 30 of them take over a second. This came up on elapouya/python-docx-template#601.

Most of it is two things. The passed object is saved to a BytesIO and reopened to get a copy, which re-zips and re-parses every part. And docxcompose rebuilds the style mapping for every subdoc by creating a python-docx Style object for each style of both documents.

What you'd like

Copy only the body XML, since that's the only part that gets changed, and read the style ids and names straight from the styles XML. Same output, just faster.

Alternatives you've tried

Saving to BytesIO yourself and passing the stream is about the same speed, it's what new_subdoc() does internally now.

Activity

  1. added
    enhancement
    on Nov 23, 2026
  2. cvas22 commented on Nov 23, 2026

    @cvas22
    OwnerAuthor

    @aiprogramming I opened #202 for this, inserting a rendered sub-template or an in-memory Document gets about 5x faster per subdoc.

  3. cvas22 commented on Nov 23, 2026

    @cvas22
    OwnerAuthor

    @aiprogramming merged in #202, in-memory and rendered sub-templates insert about 5x faster now. It'll be in the next release.

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

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions