However, we should be considering algorithmic
improvements first.
The first thing that catches my eye about this profile is the number of calls. On the
data set being used, our test query returns slightly fewer than 100 geospatial objects.
So why are we decoding geospatial objects 2,730 times? After some investigation, we
find this note in the spatial adapter??™s code:
Because ActiveRecord keeps only the string values directly returned from the database,
it translates from these to the correct types every time an attribute is read (using
the code returned by this method), which is probably OK for simple types, but might
be less than efficient for geometries. Also, you cannot modify the geometry object
returned directly or your change will not be saved.
So, every time we reference a geospatial column (via Listing#location), it is being
decoded again from the string representation. We can do better than that. We will
keep a cache of the last-seen string value (the EWKB value from PostGIS), as well as
its corresponding geometry (the Ruby object). This is done by inserting the following
code into the Listing class:
class Listing
# Cache location information
# AR wants to cast the HexEWKB string to a Geometry on each access,
# let's not do that
def location
string = location_before_type_cast
return @location_geometry if string == @location_string
@location_string = string
@location_geometry = super
Figure 6-4.
Pages:
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248