Small improvements: moved objet creation outside the loop when possible + made some classes explicitly immutable