# frozen_string_literal: true
# require 'pry-byebug'
require 'benchmark'
require 'benchmark/ips'
require 'benchmark/memory'
puts '```ruby'
puts File.read(__FILE__).gsub("\t", ' ')
puts '```'
puts
puts '### Output'
puts
puts '```'
module MyRbConfig
CONFIG = { 'ruby_install_name' => 'jruby' }
end
class PlatformA
def jruby?
MyRbConfig::CONFIG['ruby_install_name'] == 'jruby'
end
end
class PlatformB
case MyRbConfig::CONFIG['ruby_install_name']
when 'jruby'
def jruby?; true; end
else
def jruby?; false; end
end
end
class PlatformC
def jruby?
return @jruby if defined? @jruby
@jruby = MyRbConfig::CONFIG['ruby_install_name'] == 'jruby'
end
end
class PlatformD
IS_JRUBY = MyRbConfig::CONFIG['ruby_install_name'] == 'jruby'
private_constant :IS_JRUBY
def jruby?
IS_JRUBY
end
end
def via_simple_method
PlatformA.new.jruby?
end
def via_inline_method
PlatformB.new.jruby?
end
def via_memoization
PlatformC.new.jruby?
end
def via_constant
PlatformD.new.jruby?
end
def test
exit if p(pp([
via_simple_method,
via_inline_method,
via_memoization,
via_constant
]).uniq.size) > 1
end
test
Benchmark.ips do |x|
x.report('via_simple_method') { via_simple_method }
x.report('via_inline_method') { via_inline_method }
x.report('via_memoization') { via_memoization }
x.report('via_constant') { via_constant }
x.compare!
end
Benchmark.memory do |x|
x.report('via_simple_method') { 100.times { via_simple_method } }
x.report('via_inline_method') { 100.times { via_inline_method } }
x.report('via_memoization') { 100.times { via_memoization } }
x.report('via_constant') { 100.times { via_constant } }
x.compare!
end
puts '```'
[true, true, true, true]
1
Warming up --------------------------------------
via_simple_method 307.877k i/100ms
via_inline_method 359.601k i/100ms
via_memoization 263.984k i/100ms
via_constant 353.513k i/100ms
Calculating -------------------------------------
via_simple_method 5.094M (± 0.7%) i/s - 25.554M in 5.016296s
via_inline_method 6.216M (± 1.7%) i/s - 31.285M in 5.034356s
via_memoization 4.155M (± 1.4%) i/s - 20.855M in 5.019941s
via_constant 6.450M (± 1.0%) i/s - 32.523M in 5.042713s
Comparison:
via_constant: 6450142.1 i/s
via_inline_method: 6216235.8 i/s - 1.04x slower
via_simple_method: 5094405.0 i/s - 1.27x slower
via_memoization: 4155210.7 i/s - 1.55x slower
Calculating -------------------------------------
via_simple_method 4.000k memsize ( 0.000 retained)
100.000 objects ( 0.000 retained)
0.000 strings ( 0.000 retained)
via_inline_method 4.000k memsize ( 0.000 retained)
100.000 objects ( 0.000 retained)
0.000 strings ( 0.000 retained)
via_memoization 4.000k memsize ( 0.000 retained)
100.000 objects ( 0.000 retained)
0.000 strings ( 0.000 retained)
via_constant 4.000k memsize ( 0.000 retained)
100.000 objects ( 0.000 retained)
0.000 strings ( 0.000 retained)
Comparison:
via_simple_method: 4000 allocated
via_inline_method: 4000 allocated - same
via_memoization: 4000 allocated - same
via_constant: 4000 allocated - same