Some refactoring to increase the performance of the count function.