Created
May 14, 2018 12:35
-
-
Save d-Pixie/52320c22fad3407630682a13925f239d to your computer and use it in GitHub Desktop.
Ruby code for benchmarking JSON generation from Rails models. You need to install these gems before running: `gem install rails rabl jbuilder roar ffaker`. Based on https://gist.github.com/mimosa/ac14b3527c33bf767dc11875ce3964b8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'bundler' | |
require 'active_model_serializers' | |
require 'roar/decorator' | |
require 'roar/json' | |
require 'rabl' | |
require 'jbuilder' | |
require 'benchmark' | |
require 'ffaker' | |
class Post | |
include ActiveModel::Model | |
include ActiveModel::Serializers::JSON | |
attr_accessor :id, :author, :body, :draft | |
end | |
posts = [] | |
(1..100_000).each do |id| | |
posts << Post.new(id: id, author: FFaker::Name.name, body: FFaker::HipsterIpsum.paragraph, draft: [true, false].sample) | |
end | |
class PostSerializer < ActiveModel::Serializer | |
attributes :id, :author, :body, :draft | |
end | |
module PostsRepresenter | |
include Roar::JSON | |
property :id | |
property :author | |
property :body | |
property :draft | |
end | |
def rabl_template | |
' | |
collection @posts | |
attributes :id, :author, :body, :draft | |
' | |
end | |
puts '_' * 88 | |
def ams_test(posts) | |
ActiveModel::Serializer::CollectionSerializer.new(posts, each_serializer: PostSerializer).to_json | |
end | |
def roar_test(posts) | |
PostsRepresenter.for_collection.prepare(posts).to_json | |
end | |
def rabl_test(posts) | |
Rabl.render(posts, rabl_template) | |
end | |
def jbuilder_test(posts) | |
Jbuilder.encode do |json| | |
json.array! posts, :id, :author, :body, :draft | |
end | |
end | |
def to_json_test(posts) | |
posts.map(&:to_json).to_json | |
end | |
puts 'with 100_000 records' | |
Benchmark.bm do |x| | |
x.report('AMS') { ams_test(posts) } | |
x.report('Roar') { roar_test(posts) } | |
x.report('RABL') { rabl_test(posts) } | |
x.report('JB') { jbuilder_test(posts) } | |
x.report('to_json') { to_json_test(posts) } | |
end | |
puts "with 2000 records" | |
first2k = posts.take(2000) | |
Benchmark.bm do |x| | |
x.report('AMS') { ams_test(first2k) } | |
x.report('Roar') { roar_test(first2k) } | |
x.report('RABL') { rabl_test(first2k) } | |
x.report('JB') { jbuilder_test(first2k) } | |
x.report('to_json') { to_json_test(first2k) } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment