Skip to content

Instantly share code, notes, and snippets.

@3zcurdia
Last active November 28, 2018 20:46
Show Gist options
  • Save 3zcurdia/f1cda57cf5a582bd2ca5f0e14f6ba75f to your computer and use it in GitHub Desktop.
Save 3zcurdia/f1cda57cf5a582bd2ca5f0e14f6ba75f to your computer and use it in GitHub Desktop.
Ruby Serializers benchmark
source "https://rubygems.org"
git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
ruby '2.3.8'
# Specify your gem's dependencies in ams_vs_jbuilder.gemspec
gemspec
gem 'benchmark-ips'
gem 'active_model_serializers', '0.9.4'
gem 'jbuilder'
gem 'oj'
gem 'faker'
require 'rubygems'
require 'bundler/setup'
Bundler.require
require 'json'
class Movie
attr_accessor :id, :name, :descritpion, :uuid, :score, :meta, :created_at
end
class MovieSerializer < ActiveModel::Serializer
attributes :id, :name, :descritpion, :uuid, :score, :meta, :created_at
end
movies = 1_000.times.map do |i|
movie = Movie.new
movie.id = i
movie.name = Faker::Lorem.words(2).join(" "),
movie.descritpion = Faker::Lorem.paragraphs
movie.uuid = SecureRandom.uuid
movie.score = SecureRandom.random_number(10.0)
movie.meta = { director: Faker::Name.name, country: Faker::FunnyName.name }
movie.created_at = DateTime.now
movie
end
movie = movies.sample
puts "Single object"
Benchmark.ips do |x|
x.report 'to_json' do
movie.to_json
end
x.report 'jbuilder' do
Jbuilder.encode do |json|
json.id movie.id
json.name movie.name
json.descritpion movie.descritpion
json.uuid movie.uuid
json.score movie.score
json.meta movie.meta
json.created_at movie.created_at
end
end
x.report 'AMS' do
MovieSerializer.new(movie).to_json
end
x.compare!
end
puts "Array of objects"
Benchmark.ips do |x|
x.report 'to_json' do
movies.to_json
end
x.report 'jbuilder' do
Jbuilder.encode do |json|
json.array! movies do |sec|
json.id movie.id
json.name movie.name
json.descritpion movie.descritpion
json.uuid movie.uuid
json.score movie.score
json.meta movie.meta
json.created_at movie.created_at
end
end
end
x.report 'AMS' do
# TODO: unsolve this mistery
# ActiveModel::ArraySerializer.new(movies, each_serializer: MovieSerializer)
end
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment