Optimize nearest neighbor function.