Refactor

This is how I would have done it - it's slightly faster, and uses less memory. Can you figure out why?