manim icon indicating copy to clipboard operation
manim copied to clipboard

Mobject: __iter__, __len__, and __getitem__ make a copy of self.submobjects on every call

Open nikolajmunk opened this issue 3 months ago • 0 comments

Problem description

All three of Mobject.__iter__, Mobject.__len__, and Mobject.__getitem__ operate on the output of self.split(), which is implemented like so:

def split(self) -> list[Mobject]:
    result: list[Mobject] = [self] if len(self.points) > 0 else []
    return result + self.submobjects

As a result, a new list created from self.submobjects (and possibly self) is built every time one of these methods is called, leading to an unnecessary use of both time and memory. The problem is especially egregious in the case of __len__ and __getitem__, which reasonably should have constant-time access but instead have O(N) time (and space?) complexity for N submobjects.

Benchmark

As a super quick test, I measured the running time of constructing each of the three lists in the following:

# PseudoPython; I did this more intelligently IRL
for n in np.linspace(10, 200_000, 10):
    mob = VGroup(Circle() for _ in range(n))

    # measure each of these
    a = [*mob]
    b = [*mob.submobjects]
    c = [mob[i] for i in range(len(mob.submobjects))]

The results look like this: Image I haven't measured memory usage.

Other comments

Curiously, this only seems to be an issue for Mobject; in OpenGLMobject, split is implemented as follows:

def split(self) -> Sequence[OpenGLMobject]:
    return self.submobjects

It's not clear to me whether this different in the behavior of split is intended or accidental. That's maybe one for a separate issue.

nikolajmunk avatar Aug 05 '26 12:08 nikolajmunk