Skip to content

Instantly share code, notes, and snippets.

@mimosa
Created October 11, 2017 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mimosa/6bc8711b7f88d7845222fbf89e130ae7 to your computer and use it in GitHub Desktop.
Save mimosa/6bc8711b7f88d7845222fbf89e130ae7 to your computer and use it in GitHub Desktop.
active_model_serializers VS rabl
# frozen_string_literal: true
require 'oj'
require 'rabl'
require 'active_model_serializers'
require 'benchmark/memory'
require 'benchmark/ips'
Rabl.configure do |c|
c.view_paths << 'app/views'
c.json_engine = Oj if defined?(Oj)
end
ActiveModelSerializers.logger.level = Logger::Severity::UNKNOWN
class ArrayStruct
def self.new(ary = [])
ary.map { |hash| OpenStruct.new(hash) }
end
end
users = [
{ name: 'Bob', age: 27, year: 1976 },
{ name: 'MMM', age: 21, year: 1996 },
{ name: 'NNN', age: 24, year: 1936 },
{ name: 'DDD', age: 25, year: 1978 },
]
class UserSerializer < ActiveModel::Serializer
attributes :name, :age, :year
def read_attribute_for_serialization(attr)
try(attr) || object.send(attr)
end
def year
'1980'
end
end
def ruby_map(users)
ActiveModelSerializers::SerializableResource.new(
users,
each_serializer: UserSerializer
).as_json
end
def rabl_render(users)
Rabl.render(users, 'welcome/index', format: :hash)
end
puts "\n"
users = ArrayStruct.new(users)
Benchmark.memory do |x|
x.report('Ruby') { 10_000.times { ruby_map(users) } }
x.report('Rabl') { 10_000.times { rabl_render(users) } }
x.compare!
end
puts "---------------------------------------------\n\n"
Benchmark.ips do |x|
x.report('Ruby') { ruby_map(users) }
x.report('Rabl') { rabl_render(users) }
x.compare!
end
puts "\n"
# app/views/welcome/index.json.rabl
collection :users
attributes :name, :age
node :year do
'1980'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment