Surus 0.4.0 Released

Posted on 02/22/2013

Surus is a Ruby gem that adds PostgreSQL specific functions to ActiveRecord to greatly improve the performance of certain data operations. Surus 0.4.0 adds native PostgreSQL JSON generation.

PostgreSQL 9.2 added row_to_json and array_to_json functions. These functions can be used to build JSON very quickly. Unfortunately, they are somewhat cumbersome to use. The find_json and all_json methods are easy to use wrappers around the lower level PostgreSQL functions that closely mimic the Rails to_json interface.

User.find_json 1
User.find_json 1, columns: [:id, :name, :email]
Post.find_json 1, include: :author
User.find_json(user.id, include: {posts: {columns: [:id, :subject]}})
User.all_json
User.where(admin: true).all_json
User.all_json(columns: [:id, :name, :email], include: {posts: {columns: [:id, :subject]}})
Post.all_json(include: [:forum, :post])

The speedup can be anything from a few percent for small objects to many times faster for large object graphs.

jack@hk-47~/dev/surus$ ruby -I lib -I bench bench/json_generation.rb
Generating test data... Done.
                                                              user     system      total        real
find_json: 1 record 500 times                             0.140000   0.010000   0.150000 (  0.205195)
to_json:   1 record 500 times                             0.240000   0.010000   0.250000 (  0.287435)
find_json: 1 record with 3 associations 500 times         0.480000   0.010000   0.490000 (  0.796025)
to_json:   1 record with 3 associations 500 times         1.130000   0.050000   1.180000 (  1.500837)
all_json:  50 records with 3 associations 20 times        0.030000   0.000000   0.030000 (  0.090454)
to_json:   50 records with 3 associations 20 times        1.350000   0.020000   1.370000 (  1.710151)

Read more about the underlying technology at the Hashrocket blog. Get the code at Github.

blog comments powered by Disqus