codecation/trailmix — pull request #121 by chrishunt (2014-10-11 16:07:12+00:00)
Title: Let the db find us a random entry; it's faster.

Every time we send someone a daily email, we're [loading all their entries](https://github.com/codecation/trailmix/blob/443b102136ae379c0e23ce0bb25894374f758dec/app/models/user.rb#L31) into memory in order to select one at random. For some users who have a couple thousand entries already, this is not ideal. :grin:

PostgreSQL to the rescue! See this very detailed and scientific benchmark (on staging):

```ruby
> def time
> start = Time.current
>
> yield
>
> puts "#{(Time.current - start).round(3)} seconds"
> end

> user.entries.count
=> 1482

> time { user.entries.sample }
0.128 seconds

> time { user.entries.order("RANDOM()").first }
0.007 seconds
```