-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbenchmark.rb
More file actions
144 lines (84 loc) · 1.88 KB
/
Copy pathbenchmark.rb
File metadata and controls
144 lines (84 loc) · 1.88 KB
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
require "benchmark"
N_FIELDS = 100
N_OBJS = 1_000
FIELDS = (1..N_FIELDS).map { |i| :"f#{i}" }
TEMPLATE = FIELDS.map { |k| [k, nil] }.to_h.freeze
INDEX = FIELDS.each_with_index.to_h
Row = Struct.new(*FIELDS)
def bench(label)
t = Benchmark.realtime { yield }
puts "%-28s %0.4f sec" % [label, t]
end
# -----------------------------
# 0) Hash#keys
# -----------------------------
bench("Hash#keys") do
N_OBJS.times do
h = {}
FIELDS.each { |k| h[k] = 1 }
end
end
# -----------------------------
# 1) Hash#replace
# -----------------------------
bench("Hash#replace + assign") do
N_OBJS.times do
h = {}
h.replace(TEMPLATE)
FIELDS.each { |k| h[k] = 1 }
end
end
# -----------------------------
# 2) Struct
# -----------------------------
bench("Struct.new + assign") do
N_OBJS.times do
r = Row.new
FIELDS.each { |k| r[k] = 1 }
end
end
# -----------------------------
# 3) Array + index map
# -----------------------------
bench("Array + index map") do
N_OBJS.times do
arr = Array.new(N_FIELDS)
FIELDS.each { |k| arr[INDEX[k]] = 1 }
end
end
# -----------------------------
# 4) Struct -> Hash at boundary
# -----------------------------
bench("Struct + to_h") do
N_OBJS.times do
r = Row.new
FIELDS.each { |k| r[k] = 1 }
r.to_h
end
end
FIELDS2 = [:id, :name, :email, :posts]
INDEX2 = { id: 0, name: 1, email: 2, posts: 3 }
keys = ["id", "name", "email", "posts"].map(&:freeze)
bench("Build via Hash") do
N_OBJS.times do
h = {}
h[keys[0]] = nil
h[keys[1]] = nil
h[keys[2]] = nil
h[keys[3]] = 3
h[keys[0]] = 0
h[keys[2]] = 2
h[keys[1]] = 1
end
end
bench("Build via Array / Hash") do
N_OBJS.times do
arr = Array.new(keys.length)
arr[3] = 3
arr[0] = 0
arr[1] = 1
arr[2] = 2
h = {}
FIELDS2.each_with_index { |k,i| h[k] = arr[i]}
end
end