optimized distance calculator