Performance improvements.

Here is an updated pull request with the fixes needed for the tests to pass.