Skip to content

Instantly share code, notes, and snippets.

@davydovanton
Last active November 11, 2018 13:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davydovanton/dd0ba7930bf6725146171363c99aace3 to your computer and use it in GitHub Desktop.
Save davydovanton/dd0ba7930bf6725146171363c99aace3 to your computer and use it in GitHub Desktop.
Benchmark: each_with_object vs map!
require 'benchmark/ips'
array = (1..10_000).to_a
Benchmark.ips do |x|
x.report('each_with_object') { array.each_with_object([]) { |i,a| a << (i * 2) } }
x.report('map') { array.map { |i| i * 2 } }
x.report('map!') { array.map! { |i| i * 2 } }
x.report('reduse') { array.reduce([]) { |a,i| a << i * 2 } }
x.compare!
end
# Warming up --------------------------------------
# each_with_object 75.000 i/100ms
# map 132.000 i/100ms
# map! 24.000 i/100ms
# reduse 17.000 i/100ms
# Calculating -------------------------------------
# each_with_object 156.681 (±19.8%) i/s - 825.000 in 5.563924s
# map 201.255 (± 4.0%) i/s - 1.056k in 5.254692s
# map! 179.438 (±11.7%) i/s - 888.000
# reduse 165.944 (± 5.4%) i/s - 833.000
#
# Comparison:
# map: 201.3 i/s
# map!: 179.4 i/s - 1.12x slower
# reduse: 165.9 i/s - 1.21x slower
# each_with_object: 156.7 i/s - 1.28x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment