Show only stores within 10 km. Building a point from longitude and latitude for every row costs time (~170 ms).
Query time
~170 ms~70 ms
59% lower
about 100 ms faster
Eloquent performanceLesson 26 of 28
Precompute geometry once instead of on every query.
1 min readIntermediateLesson
Show only stores within 10 km. Building a point from longitude and latitude for every row costs time (~170 ms).
Store a precomputed spatial point column and compare against that.
$query->whereRaw(
'ST_Distance(ST_SRID(Point(longitude, latitude), 4326), ST_SRID(Point(?, ?), 4326)) <= ?',
[...$coordinates, $distance]
);
// builds a point for every row, every query
$query->whereRaw(
'ST_Distance(location, ST_SRID(Point(?, ?), 4326)) <= ?',
[...$coordinates, $distance]
);
About 100 ms faster, because the point is stored once rather than rebuilt on every query.
Query time
~170 ms~70 ms
59% lower
about 100 ms faster
The migration replaces the two number columns with one point column:
$table->point('location', 4326);
DB::raw("ST_SRID(Point($lng, $lat), 4326)") is fine for a trusted file. Never put user input in raw SQL. Use bindings.
The seeder writes a precomputed point: 'location' => DB::raw('ST_SRID(Point(lng, lat), 4326)'). Inlining values like this is fine for a trusted CSV, but never for user input.
Precompute geometry once instead of on every query.
Why did switching to a point column speed things up?
✓ Answer
The point no longer has to be built from two numbers for every row on every query.