Registry Mirror
搜索
Skip to content
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
Files
Expand file tree
main
Breadcrumbs
fast-ruby
/
code
/
general
/
define_method-vs-module-eval.rb
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
35 lines (31 loc) · 873 Bytes
main
Breadcrumbs
fast-ruby
/
code
/
general
/
define_method-vs-module-eval.rb
Copy path
Top
File metadata and controls
Code
Blame
35 lines (31 loc) · 873 Bytes
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
require 'benchmark/ips'
# Built once, so the benchmark measures defining the methods, not building names.
# Random names built on every call made garbage, and the GC paused at random moments.
METHOD_NAMES = Array.new(10) { |i| "method_#{i}" }
# Each call defines the 10 methods on a new, empty class, so every call does the same work.
# Adding them to one class that is never reset made late calls slower than early ones.
def fast
Class.new do
METHOD_NAMES.each do |method_name|
define_method method_name do
puts 'win'
end
end
end
end
def slow
Class.new do
METHOD_NAMES.each do |method_name|
module_eval %{
def #{method_name}
puts "win"
end
}
end
end
end
Benchmark.ips do |x|
x.report('define_method') { fast }
x.report('module_eval with string') { slow }
x.compare!
end
You can’t perform that action at this time.