기존에 사용자의 위치(위도,경도)와 DB에 저장된 장소별 위치(위도,경도)의 거리의 차를 구해야하는 상황에서 haversine이라는 라이브러리를 찾아서 사용하고 있던 중에 mysql에 haversine이라는 쿼리가 있었다. 아무래도 DB에 있는 기능이므로 사용하면 뭔가 더 빠르게 적은 쿼리수로 호출이 가능한가 싶어서 비교를 해봤다.
haversine 라이브러리 vs Mysql GIS 공간 쿼리 → haversine 사용
상황: 사용자의 위치(위도,경도)와 DB에 저장된 장소별 위치(위도,경도)의 거리의 차를 구해야하는 상황
- 평균 속도 45.4ms, 호출 데이터 양 11.1KB


const latitude = ((Number(qa) + Number(pa)) / 2).toFixed(10)
const longitude = ((Number(ha) + Number(oa)) / 2).toFixed(10)
// // 거리 계산 및 정렬
const start = {
latitude: +latitude || qa,
longitude: +longitude || ha
}
// 게시글 개수, 거리차 추가
const locationsWithDistance = await Promise.all(
location.map(async (loc) => {
const distance = +haversine(
start,
{ latitude: loc.latitude, longitude: loc.longitude },
{ unit: "meter" },
).toFixed(10);
return {
distance,
...loc
};
}),
);
- 평균 속도 89.7ms, 호출 데이터 양 11.3KB


const latitude = ((Number(qa) + Number(pa)) / 2).toFixed(10)
const longitude = ((Number(ha) + Number(oa)) / 2).toFixed(10)
const locationsWithDistance = await Promise.all(
location.map(async (loc) => {
const distance = await prisma.$queryRaw`SELECT ST_Distance_Sphere(POINT(${longitude},${latitude}),POINT(${loc.longitude},${loc.latitude})) as 'distance'`
return {
distance,
...loc
}
}),
)
haversine보다 GIS 쿼리를 사용했을 때 호출되는 쿼리양도 많고(호출되는 데이터도 많음), 평균 호출 속도가 느림. ⇒ haversine 라이브러리를 사용하기로 결정.

| 방법 | 회차 | 1 | 2 | 3 | 4 | 5 | 평균 | 호출데이터 |
|---|---|---|---|---|---|---|---|---|
| 속도(ms) | GIS 쿼리사용 | 142 | 75 | 63.6 | 85.2 | 82.7 | 89.7 | 11.3KB |
| haversine 사용 | 82.4 | 41.3 | 40.5 | 33.9 | 29.1 | 45.44 | 11.1KB |