optimizing code for stacking of tables