Trading memory for speed: 10x speedup wrt the first implementation