Skip to content

Instantly share code, notes, and snippets.

@bibendi
Created October 25, 2017 06:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bibendi/dfea7f33ec61db85b4dc895e5c68456c to your computer and use it in GitHub Desktop.
Save bibendi/dfea7f33ec61db85b4dc895e5c68456c to your computer and use it in GitHub Desktop.
Compare map vs map!
key = "id".freeze
rows = []
5000.times { rows << {"id" => rand(5000).to_s} }
require 'benchmark/ips'
Benchmark.ips do |x|
x.report('map') { rows.dup.map { |r| r[key].to_i } }
x.report('map!') { rows.dup.map! { |r| r[key].to_i } }
x.compare!
end
require 'benchmark/memory'
Benchmark.memory do |x|
x.report('map') { rows.dup.map { |r| r[key].to_i } }
x.report('map!') { rows.dup.map! { |r| r[key].to_i } }
x.compare!
end
@bibendi
Copy link
Author

bibendi commented Oct 25, 2017

Calculating -------------------------------------
                 map    963.373  (± 3.7%) i/s -      4.888k in   5.081362s
                map!    996.699  (± 4.8%) i/s -      5.050k in   5.079215s

Comparison:
                map!:      996.7 i/s
                 map:      963.4 i/s - same-ish: difference falls within error
Comparison:
                map!:      40040 allocated
                 map:      40080 allocated - 1.00x more

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment