Skip to content

Instantly share code, notes, and snippets.

@yuki24
Last active April 16, 2016 20:05
Show Gist options
  • Save yuki24/4604675 to your computer and use it in GitHub Desktop.
Save yuki24/4604675 to your computer and use it in GitHub Desktop.
Jbuilder is faster than Ralb.
require 'benchmark'
require 'active_support/core_ext'
require 'jbuilder'
require 'rabl'
require 'oj'
require 'multi_json'
Benchmark.bm(25) do |benchmark|
struct = Struct.new(:name, :birthyear, :bio, :url)
@author = struct.new("Rolf", 1920, "Software developer", "http://example.com/")
@authors = Array.new(10, @author)
# for jbuilder
@author.instance_eval { undef map }
# for rabl
@scope = Object.new
@scope.instance_variable_set :@author, @author
@scope.instance_variable_set :@authors, @authors
benchmark.report "Jbuilder(single object)" do
10000.times do
json = Jbuilder.encode do |json|
json.author @author, :name, :birthyear, :bio, :url
end
end
end
benchmark.report "Rabl(single object)" do
template = %{
object @author => :author
attribute :name, :birthyear, :bio, :url
}
10000.times do
Rabl::Engine.new(template).render(@scope, {})
end
end
benchmark.report "Jbuilder(collection)" do
10000.times do
json = Jbuilder.encode do |json|
json.authors @authors do |author|
json.author author, :name, :birthyear, :bio, :url
end
end
end
end
benchmark.report "Rabl(collection)" do
template = %{
collection @authors => :authors
attributes :name, :birthyear, :bio, :url
}
10000.times do
Rabl::Engine.new(template).render(@scope, {})
end
end
end
@yuki24
Copy link
Author

yuki24 commented Jan 23, 2013

Result(from the revesion d0696b8d):

                                user     system      total        real
Jbuilder(single object)     1.040000   0.000000   1.040000 (  1.045209)
Rabl(single object)         2.350000   0.000000   2.350000 (  2.368760)
Jbuilder(collection)        2.780000   0.000000   2.780000 (  2.798979)
Rabl(collection)           12.910000   0.020000  12.930000 ( 12.972485)

@yuki24
Copy link
Author

yuki24 commented Feb 3, 2014

updated the code/gems and ran the above again(higher is better):

$ bundle exec ruby benchmark.rb 
Calculating -------------------------------------
Jbuilder(single obj)      2932 i/100ms
    Rabl(single obj)       870 i/100ms
Jbuilder(collection)       984 i/100ms
    Rabl(collection)       273 i/100ms
-------------------------------------------------
Jbuilder(single obj)    42435.5 (±5.0%) i/s -     214036 in   5.058724s
    Rabl(single obj)    10409.0 (±5.7%) i/s -      52200 in   5.031122s
Jbuilder(collection)    11913.3 (±4.0%) i/s -      60024 in   5.046583s
    Rabl(collection)     2817.2 (±10.2%) i/s -      13923 in   5.017393s

Ruby version:

$ ruby -v
ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-linux]

jbuilder is almost 4 times faster than rabl.

@constantm
Copy link

I wonder if these benchmarks still hold.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment