Created
May 19, 2015 23:17
-
-
Save janko/4d3603f0bde5dd26b00b to your computer and use it in GitHub Desktop.
Serialization performance
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
gem "active_model_serializers", "0.10.0.rc1" | |
require "yaks" | |
require "active_record" | |
require "active_model_serializers" | |
require "benchmark/ips" | |
ActiveRecord::Base.establish_connection(adapter: "postgresql", database: "testing") | |
ActiveRecord::Schema.define do | |
create_table :users, force: true do |t| | |
t.string :first_name | |
t.string :last_name | |
t.string :email | |
t.string :password | |
t.date :date_of_birth | |
t.timestamps null: false | |
end | |
end | |
class User < ActiveRecord::Base | |
end | |
user = User.create( | |
first_name: "Janko", | |
last_name: "Marohnić", | |
email: "janko.marohnic@gmail.com", | |
password: "secret", | |
date_of_birth: Date.new(1991, 3, 10), | |
) | |
class UserMapper < Yaks::Mapper | |
attributes *User.column_names | |
end | |
class UserSerializer < ActiveModel::Serializer | |
attributes *User.column_names | |
end | |
yaks = Yaks.new do | |
default_format :json_api | |
map_to_primitive Date, Time, &:iso8601 | |
end | |
Benchmark.ips do |x| | |
x.report("yaks") { yaks.call(user, mapper: UserMapper) } | |
x.report("ams") do | |
serializer = UserSerializer.new(user) | |
adapter = ActiveModel::Serializer::Adapter::JsonApi | |
adapter.new(serializer).as_json | |
end | |
x.report("database") { User.all.to_a } | |
x.compare! | |
end | |
# ams: 10048.9 i/s | |
# database: 3069.7 i/s - 3.27x slower | |
# yaks: 2430.1 i/s - 4.14x slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment