Skip to content

Commit 1c9a76a

Browse files
committed
1 parent 1301b52 commit 1c9a76a

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

bench/perf.rb

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
require 'rubygems'
2+
require 'bundler/setup'
3+
require 'rails/railtie'
4+
require 'active_model_serializers'
5+
require 'active_support/json'
6+
require 'benchmark'
7+
8+
class User < Struct.new(:id, :name, :age, :about)
9+
include ActiveModel::Serialization
10+
11+
def fast_hash
12+
h = {
13+
id: read_attribute_for_serialization(:id),
14+
name: read_attribute_for_serialization(:name),
15+
about: read_attribute_for_serialization(:about)
16+
}
17+
h[:age] = read_attribute_for_serialization(:age) if age > 18
18+
h
19+
end
20+
end
21+
22+
class UserSerializer < ActiveModel::Serializer
23+
attributes :id, :name, :age, :about
24+
25+
def include_age?
26+
object.age > 18
27+
end
28+
end
29+
30+
u = User.new(1, 'sam', 10, 'about')
31+
s = UserSerializer.new(u)
32+
33+
n = 100000
34+
35+
Benchmark.bmbm do|x|
36+
x.report('init') { n.times { UserSerializer.new(u) } }
37+
x.report('fast_hash') { n.times { u.fast_hash } }
38+
x.report('attributes') { n.times { UserSerializer.new(u).attributes } }
39+
# x.report("serializable_hash") { n.times { u.serializable_hash } }
40+
end

0 commit comments

Comments
 (0)