Created
November 26, 2019 20:25
-
-
Save arieliten/93e1fe021a2561127b530e23179da4dd to your computer and use it in GitHub Desktop.
Ruby (Rails) Json parsers comparisson
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_support/core_ext/object/deep_dup' | |
require 'active_model_serializers' | |
require 'roar/decorator' | |
require 'roar/json' | |
require 'rabl' | |
require 'jbuilder' | |
require 'fast_jsonapi' | |
require 'benchmark' | |
require 'ffaker' | |
require 'multi_json' | |
require 'oj' | |
# MultiJson.use :json_gem | |
MultiJson.use :oj | |
Post = Struct.new(:id, :author, :body, :draft) do | |
include ActiveModel::Serializers::JSON | |
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 | |
class PostNetflixSerializer | |
include FastJsonapi::ObjectSerializer | |
set_type :post | |
attributes :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 fast_jsonapi_test(posts) | |
PostNetflixSerializer.new(posts).serialized_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 | |
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('Jbuilder ') { jbuilder_test(posts) } | |
x.report('fast_jsonapi ') { fast_jsonapi_test(posts) } | |
end | |
puts '_' * 88 | |
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('Jbuilder ') { jbuilder_test(first2k) } | |
x.report('fast_jsonapi ') { fast_jsonapi_test(first2k) } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment