Sort out memory management of plans with the optimizer.

Slightly adapt optimization strategy.