Optimization of distance calculation