A million objects: make fewer of them

Part 1 made each tree smaller. This part makes fewer objects instead. You only need this when two things are true: you have a lot of objects, and a big part of each one is the same as in many others. A million trees with three species qualify. A thousand trees don’t, and neither do a million trees that are all different. The problem In a game, a tree also needs to look like something. Say the forest now comes from a file, and every tree has a species with a colour and a texture: ...

A million objects: where do the bytes go?

Say you’re simulating a forest: a million trees, each with a position and an age. class Tree: def __init__(self, x, y, age): self.x = x self.y = y self.age = age Three small ints per tree. In C that’s 12–24 bytes a tree, so a million trees would take about 24 MB. In Python 3.10 the same million trees take 152 MB. In 3.13 they take 96 MB, without changing a line. There are two ways to make a million objects cheap: make each object smaller, or make fewer objects. This post is about the first one. It covers where those bytes go, what __slots__ removes, and how much of that CPython 3.11+ now does for you. ...