Skip to content

Instantly share code, notes, and snippets.

@gmarik

gmarik/code.rb Secret

Last active Feb 9, 2016
Embed
What would you like to do?
immutable-vs-mutable? Both!
CAT_TO_ITEM_MAP = {
'numbers' => %w[0 1 2 3],
'letters' => %w[a b c d],
}
def items_to_categories_map_immutable
reducer = -> (acc, (cat, items)) do
items.reduce(acc) { |acc, item| acc.merge(item => cat) }
end
CAT_TO_ITEM_MAP.reduce({}, &reducer)
end
def items_to_categories_map_mutable
acc = {}
reducer = -> (cat, items) do
items.each { |item| acc[item] = cat }
end
CAT_TO_ITEM_MAP.each(&reducer)
acc
end
if __FILE__ == $0
require 'benchmark'
require 'test/unit'
include Test::Unit::Assertions
val = {
"0"=>"numbers",
"1"=>"numbers",
"2"=>"numbers",
"3"=>"numbers",
"a"=>"letters",
"b"=>"letters",
"c"=>"letters",
"d"=>"letters"
}
assert_equal val, items_to_categories_map_immutable
assert_equal val, items_to_categories_map_mutable
n = 500000
Benchmark.bm(10) do |x|
x.report("mutable") { n.times { items_to_categories_map_mutable } }
x.report("immutable") { n.times { items_to_categories_map_immutable } }
end
end
# $ ruby test.rb
# user system total real
# mutable 2.550000 0.390000 2.940000 ( 2.946557)
# immutable 7.900000 0.920000 8.820000 ( 8.842163)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment