KNN performance improvements

Squashed patch for review. See issue #44.