forked from rspec/rspec-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrespond_to_v_defined.rb
72 lines (62 loc) · 1.45 KB
/
respond_to_v_defined.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
require 'benchmark'
n = 1_000_000
puts "Kernel.respond_to?(:warn)"
Benchmark.benchmark do |bm|
3.times do
bm.report do
n.times do
Kernel.respond_to?(:warn)
end
end
end
end
puts "defined?(warn)"
Benchmark.benchmark do |bm|
3.times do
bm.report do
n.times do
defined?(warn)
end
end
end
end
puts "Kernel.respond_to?(:foo)"
Benchmark.benchmark do |bm|
3.times do
bm.report do
n.times do
Kernel.respond_to?(:foo)
end
end
end
end
puts "defined?(foo)"
Benchmark.benchmark do |bm|
3.times do
bm.report do
n.times do
defined?(foo)
end
end
end
end
# $ ruby benchmarks/respond_to_v_defined.rb
# Kernel.respond_to?(:warn)
# 0.190000 0.000000 0.190000 ( 0.206502)
# 0.190000 0.000000 0.190000 ( 0.197547)
# 0.190000 0.000000 0.190000 ( 0.189731)
# defined?(warn)
# 0.190000 0.000000 0.190000 ( 0.187334)
# 0.180000 0.000000 0.180000 ( 0.201078)
# 0.190000 0.000000 0.190000 ( 0.202295)
# Kernel.respond_to?(:foo)
# 0.250000 0.010000 0.260000 ( 0.255003)
# 0.240000 0.000000 0.240000 ( 0.247376)
# 0.250000 0.000000 0.250000 ( 0.251196)
# defined?(foo)
# 0.100000 0.000000 0.100000 ( 0.104748)
# 0.110000 0.000000 0.110000 ( 0.107250)
# 0.110000 0.000000 0.110000 ( 0.107990)
#
# defined is consistently faster, but it takes 1,000,000 x to have a meaningful
# diff