-
Notifications
You must be signed in to change notification settings - Fork 1
/
bench.rb
302 lines (239 loc) · 8.74 KB
/
bench.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# frozen_string_literal: true
# rubocop:disable Metrics/AbcSize,Metrics/MethodLength
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'activerecord', require: 'active_record'
gem 'activemodel'
gem 'sqlite3'
gem 'light_serializer'
gem 'active_model_serializers'
gem 'blueprinter'
gem 'surrealist'
gem 'benchmark-ips', require: 'benchmark/ips'
end
puts 'Gems installed and loaded!'
ActiveRecord::Base.establish_connection(
adapter: 'sqlite3',
database: ':memory:'
)
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define do
create_table :users do |table|
table.column :name, :string
table.column :email, :string
end
create_table :authors do |table|
table.column :name, :string
table.column :last_name, :string
table.column :age, :int
end
create_table :books do |table|
table.column :title, :string
table.column :year, :string
table.belongs_to :author, foreign_key: true
end
end
ActiveModelSerializers.config.adapter = :json
def random_name
('a'..'z').to_a.shuffle.join('').first(10).capitalize
end
class User < ActiveRecord::Base
include Surrealist
json_schema { { name: String, email: String } }
end
class UserLightSerializer < LightSerializer::Serializer
attributes(:name, :email)
end
class UserSerializer < ActiveModel::Serializer
attributes :name, :email
end
class UserSurrealistSerializer < Surrealist::Serializer
json_schema { { name: String, email: String } }
end
class UserAMSSerializer < ActiveModel::Serializer
attributes :name, :email
end
class UserBlueprint < Blueprinter::Base
fields :name, :email
end
### Associations ###
class BookLightSerializer < LightSerializer::Serializer
attributes(:title, :year)
end
class AuthorLightSerializer < LightSerializer::Serializer
attributes(
:name,
:last_name,
:full_name,
:age,
books: BookLightSerializer
)
end
class AuthorSurrealistSerializer < Surrealist::Serializer
json_schema do
{ name: String, last_name: String, full_name: String, age: Integer, books: Array }
end
def books
object.books.to_a
end
def full_name
"#{object.name} #{object.last_name}"
end
end
class BookSurrealistSerializer < Surrealist::Serializer
json_schema { { title: String, year: String } }
end
class BookAMSSerializer < ActiveModel::Serializer
attributes :title, :year
end
class BookBlueprint < Blueprinter::Base
fields :title, :year
end
class AuthorAMSSerializer < ActiveModel::Serializer
attributes :name, :last_name, :full_name, :age
has_many :books, serializer: BookAMSSerializer
end
class AuthorBlueprint < Blueprinter::Base
fields :name, :last_name, :age
field :full_name do |author|
"#{author.name} #{author.last_name}"
end
association :books, blueprint: BookBlueprint
end
class Author < ActiveRecord::Base
include Surrealist
surrealize_with AuthorSurrealistSerializer
has_many :books
def full_name
"#{name} #{last_name}"
end
end
class Book < ActiveRecord::Base
include Surrealist
surrealize_with BookSurrealistSerializer
belongs_to :author, required: true
end
N = 3000
N.times { User.create!(name: random_name, email: "#{random_name}@test.com") }
(N / 2).times { Author.create!(name: random_name, last_name: random_name, age: rand(80)) }
N.times { Book.create!(title: random_name, year: "19#{rand(10..99)}", author_id: rand(1..N / 2)) }
def sort(obj)
case obj
when Array then obj.map { |el| sort(el) }
when Hash then obj.transform_values { |v| sort(v) }
else obj
end
end
def check_correctness(serializers)
results = serializers.map(&:call).map { |r| sort(JSON.parse(r)) }
raise 'Results are not the same' if results.uniq.size > 1
end
def benchmark(names, serializers)
check_correctness(serializers)
Benchmark.ips do |x|
x.config(time: 5, warmup: 2)
names.zip(serializers).each { |name, proc| x.report(name, &proc) }
x.compare!
end
end
def benchmark_instance(ams_arg: '', oj_arg: '')
user = User.find(rand(1..N))
names = ["AMS#{[ams_arg, oj_arg].join(' ')}: instance",
'Surrealist: instance through .surrealize',
'Light: instance through .to_json',
'Surrealist: instance through Surrealist::Serializer',
"ActiveModel::Serializers::JSON#{oj_arg} instance",
"Blueprinter#{oj_arg}"]
serializers = [-> { UserAMSSerializer.new(user).to_json },
-> { user.surrealize },
-> { UserLightSerializer.new(user).to_json },
-> { UserSurrealistSerializer.new(user).surrealize },
-> { user.to_json(only: %i[name email]) },
-> { UserBlueprint.render(user) }]
benchmark(names, serializers)
end
def benchmark_collection(ams_arg: '', oj_arg: '')
users = User.all
names = ["AMS#{[ams_arg, oj_arg].join(' ')}: collection",
'Surrealist: collection through Surrealist.surrealize_collection()',
'Light: collection through .to_json',
'Surrealist: collection through Surrealist::Serializer',
"ActiveModel::Serializers::JSON#{oj_arg} collection",
"Blueprinter collection#{oj_arg}"]
serializers = [lambda do
ActiveModel::Serializer::CollectionSerializer.new(
users, root: nil, serializer: UserAMSSerializer
).to_json
end,
-> { Surrealist.surrealize_collection(users) },
-> { LightSerializer::SerializeCollection.new(users, serializer: UserLightSerializer).to_json },
-> { UserSurrealistSerializer.new(users).surrealize },
-> { users.to_json(only: %i[name email]) },
-> { UserBlueprint.render(users) }]
benchmark(names, serializers)
end
def benchmark_associations_instance
instance = Author.find(rand((1..(N / 2))))
names = ['AMS (associations): instance',
'Surrealist (associations): instance through .surrealize',
'Light (associations): instance through .to_json',
'Surrealist (associations): instance through Surrealist::Serializer',
'ActiveModel::Serializers::JSON (associations)',
'Blueprinter (associations)']
serializers = [-> { AuthorAMSSerializer.new(instance).to_json },
-> { instance.surrealize },
-> { AuthorLightSerializer.new(instance).to_json },
-> { AuthorSurrealistSerializer.new(instance).surrealize },
lambda do
instance.to_json(only: %i[name last_name age], methods: %i[full_name],
include: { books: { only: %i[title year] } })
end,
-> { AuthorBlueprint.render(instance) }]
benchmark(names, serializers)
end
def benchmark_associations_collection
collection = Author.all
names = ['AMS (associations): collection',
'Surrealist (associations): collection through Surrealist.surrealize_collection()',
'Light (associations): collection through .to_json',
'Surrealist (associations): collection through Surrealist::Serializer',
'ActiveModel::Serializers::JSON (associations): collection',
'Blueprinter (associations): collection']
serializers = [lambda do
ActiveModel::Serializer::CollectionSerializer.new(
collection, root: nil, serializer: AuthorAMSSerializer
).to_json
end,
-> { Surrealist.surrealize_collection(collection) },
-> { LightSerializer::SerializeCollection.new(collection, serializer: AuthorLightSerializer).to_json },
-> { AuthorSurrealistSerializer.new(collection).surrealize },
lambda do
collection.to_json(only: %i[name last_name age], methods: %i[full_name],
include: { books: { only: %i[title year] } })
end,
-> { AuthorBlueprint.render(collection) }]
benchmark(names, serializers)
end
# Default configuration
benchmark_instance
benchmark_collection
# With AMS logger turned off
puts "\n------- Turning off AMS logger -------\n"
ActiveModelSerializers.logger.level = Logger::Severity::UNKNOWN
benchmark_instance(ams_arg: '(without logging)')
benchmark_collection(ams_arg: '(without logging)')
# Associations
benchmark_associations_instance
benchmark_associations_collection
puts "\n------- Enabling Oj.optimize_rails() & Blueprinter config.generator = Oj -------\n"
Oj.optimize_rails
Blueprinter.configure do |config|
config.generator = Oj
end
benchmark_instance(ams_arg: '(without logging)', oj_arg: '(with Oj)')
benchmark_collection(ams_arg: '(without logging)', oj_arg: '(with Oj)')
# Associations
benchmark_associations_instance
benchmark_associations_collection
# rubocop:enable Metrics/AbcSize,Metrics/MethodLength