thoughtbot/paperclip — pull request #1131 by urbanautomaton (2013-01-10 16:35:22+00:00)
Title: Memoize :class and :attachment interpolations for speed

Hi,

In our app we use paperclip very heavily, and often have pages with ~100 paperclip-generated URLs on them. Doing some profiling recently, I noticed that these were very expensive, on some pages taking ~200ms in total (others seem to have noticed this too, e.g. in issue #557).

The main expense is in performing interpolations on the path/URL patterns. In particular, the `:class` and `:attachment` interpolations are very expensive, mostly (as far as I can tell) as a result of calling the `#pluralize` inflection.

As these will never change, memoizing them improves their performance significantly. The attached patch does this with some hashes stored in a nested module. For 10k calls to `#image(:original)` on an example model in our app, this resulted in about an order of magnitude improvement:

```
user system total real
without memoization: 12.120000 0.400000 12.520000 ( 12.540598)
with memoization: 1.820000 0.000000 1.820000 ( 1.829574)
```

I'm not completely happy with having the memos stored as global state like this, but as the interpolations are currently implemented as global methods on the Interpolations module, I don't see much alternative, and thought the performance gains were sufficiently large to make it worth submitting as is. I'd be very happy to hear your thoughts...

All the best,
Simon