-
Notifications
You must be signed in to change notification settings - Fork 0
/
benchmark_class_init.rb
124 lines (95 loc) · 2.18 KB
/
benchmark_class_init.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
require 'ostruct'
require 'benchmark'
require 'benchmark/ips'
COUNT = 10_000_000
NAME = "Test Name"
EMAIL = "test@example.org"
class Person
attr_accessor :name, :email
end
class PersonNamedInit
attr_accessor :name, :email
def initialize(name:, email:)
@name = name
@email = email
end
end
class PersonOrderedInit
attr_accessor :name, :email
def initialize(name, email)
@name = name
@email = email
end
end
PersonStruct = Struct.new(:name, :email)
person = Person.new
person.name = NAME
person.email = EMAIL
person_named_init = PersonNamedInit.new(name: NAME, email: EMAIL)
person_ordered_init = PersonOrderedInit.new(NAME, EMAIL)
hash = {name: NAME, email: EMAIL}
ostruct = OpenStruct.new
ostruct.name = NAME
ostruct.email = EMAIL
struct = PersonStruct.new
struct.name = NAME
struct.email = EMAIL
struct_ordered = PersonStruct.new(NAME, EMAIL)
benchmark_lambda = lambda do |x|
x.report("hash:init:") do
p = {name: NAME, email: EMAIL}
end
x.report("openstruct:init:") do
p = OpenStruct.new
p.name = NAME
p.email = EMAIL
end
x.report("struct:init:") do
p = PersonStruct.new
p.name = NAME
p.email = EMAIL
end
x.report("struct_ordered:init:") do
p = PersonStruct.new(NAME, EMAIL)
end
x.report("class:init:") do
p = Person.new
p.name = NAME
p.email = EMAIL
end
x.report("class:named:init:") do
p = PersonNamedInit.new(name: NAME, email: EMAIL)
end
x.report("class:ordered:init:") do
p = PersonOrderedInit.new(NAME, EMAIL)
end
x.report("hash:access:") do
hash[:name]
hash[:email]
end
x.report("openstruct:access:") do
ostruct.name
ostruct.email
end
x.report("struct:access:") do
struct.name
struct.email
end
x.report("struct_ordered:access:") do
struct_ordered.name
struct_ordered.email
end
x.report("class:access:") do
person.name
person.email
end
x.report("class:named:access:") do
person_named_init.name
person_named_init.email
end
x.report("class:ordered:access:") do
person_ordered_init.name
person_ordered_init.email
end
end
Benchmark.ips &benchmark_lambda