In checking a report of defined?() calls being a hot spot in a fog application, I wanted to measure that actual overhead.
Here's the very simple benchmark code:
require 'benchmark/ips'
DEFINED_CONST = true
Benchmark.ips do |x|
x.report('simple assignment') { y = 'hey' }
x.report('trivial conditional') { y = 1 > 0 ? 'hey' : 'yo' }
x.report('not defined') { y = defined?(UNDEFINED_CONST) ? 'hey' : 'yo' }
x.report('defined') { y = defined?(DEFINED_CONST) ? 'hey' : 'yo' }
end
JRuby 1.7.8 results:
Calculating -------------------------------------
simple assignment 63805 i/100ms
trivial conditional 59489 i/100ms
not defined 46229 i/100ms
defined 50926 i/100ms
-------------------------------------------------
simple assignment 5577540.4 (±8.6%) i/s - 27563760 in 4.999000s
trivial conditional 4719033.2 (±6.9%) i/s - 23438666 in 4.999000s
not defined 2507802.0 (±4.5%) i/s - 12528059 in 5.008000s
defined 3434604.0 (±5.4%) i/s - 17111136 in 5.001000s
MRI 2.0.0-p247 results:
Calculating -------------------------------------
simple assignment 136486 i/100ms
trivial conditional 135371 i/100ms
not defined 122790 i/100ms
defined 129885 i/100ms
-------------------------------------------------
simple assignment 5020796.5 (±5.4%) i/s - 24976938 in 4.991007s
trivial conditional 4605347.8 (±5.4%) i/s - 23013070 in 5.013195s
not defined 3800329.8 (±5.1%) i/s - 19032450 in 5.022079s
defined 4316981.3 (±5.0%) i/s - 21560910 in 5.007771s