Skip to content

Instantly share code, notes, and snippets.

@goalaleo
Created August 23, 2019 13:51
Show Gist options
  • Save goalaleo/a37d600b0a8f36f754417371973b95d7 to your computer and use it in GitHub Desktop.
Save goalaleo/a37d600b0a8f36f754417371973b95d7 to your computer and use it in GitHub Desktop.
Benchmark for different approaches to Exercism's ruby track resistor color duo exercise
class ResistorColorDuo
attr_reader :color_bands
COLORS = { 'black' => 0,
'brown' => 1,
'red' => 2,
'orange' => 3,
'yellow' => 4,
'green' => 5,
'blue' => 6,
'violet' => 7,
'grey' => 8,
'white' => 9 }.freeze
private_constant :COLORS
def initialize(color_bands)
@color_bands = color_bands
end
def value_map
color_bands.map { |i| COLORS[i.downcase] }
.join
.to_i
end
def value_map_without_downcase
color_bands.map { |i| COLORS[i] }
.join
.to_i
end
def value_inject
color_bands.inject(0) do |previous_band, band|
(previous_band * 10) + COLORS[band.downcase]
end
end
def value_hash_access
10*COLORS[color_bands[0]] + COLORS[color_bands[1]]
end
end
require "benchmark"
n = 1_000_000
rcd = ResistorColorDuo.new(["violet", "yellow"])
padding = 20
Benchmark.bm(padding) do |x|
x.report("value_map:") { n.times do; rcd.value_map; end }
x.report("value_map:") { n.times do; rcd.value_map_without_downcase; end }
x.report("value_inject:") { n.times do; rcd.value_inject; end }
x.report("value_hash_access:") { n.times do; rcd.value_hash_access; end }
end
# user system total real
# value_map: 1.554845 0.010573 1.565418 ( 1.615006)
# value_map: 1.319509 0.004232 1.323741 ( 1.332095)
# value_inject: 0.658793 0.002375 0.661168 ( 0.664390)
# value_hash_access: 0.225108 0.002511 0.227619 ( 0.231068)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment