memory optimization on flatting