Skip to content

Section.copy_section for n sections is O(n²) #558

Closed

Description

@drodarie

Similar to #557

Description

Section.copy_section gets slower with every child section already in the destination, so copying n sections into one parent takes O(n²) time. Copying 2,000 small sections takes about 6 minutes.
This problem was uncovered during the refactor of simulation results structure for the BSB dbbs-lab/bsb#299

Reproduction

import os, tempfile, time
import nixio

def run(n):
    with tempfile.TemporaryDirectory() as tmp:
        f = nixio.File.open(os.path.join(tmp, "f.nix"), nixio.FileMode.Overwrite)
        src = f.create_section("src", "t")
        src.create_property("p", 1)  # works around #527, see the note there
        sections = [src.create_section(f"s{i}", "t") for i in range(n)]
        dst = f.create_section("dst", "t")
        start = time.perf_counter()
        for sec in sections:
            dst.copy_section(sec)
        elapsed = time.perf_counter() - start
        f.close()
    return elapsed

for n in (250, 500, 1000, 2000):
    t = run(n)
    print(f"{n:>5} copies: {t:6.2f}s  ({t / n * 1e3:5.1f} ms per copy)")
  250 copies:   6.22s  ( 24.9 ms per copy)
  500 copies:  22.84s  ( 45.7 ms per copy)
 1000 copies:  90.29s  ( 90.3 ms per copy)
 2000 copies: 371.57s  (185.8 ms per copy)

Cause

Section.copy_section (nixio/section.py:211) returns the copy by its id:

return self.sections[sec.attrs["entity_id"]]

A lookup by id goes through H5Group.get_by_id, which goes through every child section and reads its entity_id attribute until it finds a match. That makes each copy O(n) in the number of children of the destination.

Suggested fix

Return by the name the section was copied to, as File.copy_section does:

return self.sections[name]

Environment

  • OS: Linux mint 22.3 (Ubuntu 24.04)
  • Python version: 3.12
  • Nixio version: 1.5.4
  • h5py version: 3.16.0
  • NumPy version: 2.5.3

Activity

  1. linked a pull request that will close this issueSpeeding up copying of objects #559on Oct 27, 2026
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions