Refactors impurity functions as cost functions, and improves performance.