Optimize statistics algorithm so it uses less ram