Improve `_flatten()`.

Hello leaf,

Hopefully this should be faster and lighter on memory.