Optimized distance calculation