Performance and memory improvements.

Nothing fancy; mostly cleaning loose references and reordering
allocations.