Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created September 14, 2012 22:42
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 havenwood/3725426 to your computer and use it in GitHub Desktop.
Save havenwood/3725426 to your computer and use it in GitHub Desktop.
Benchmark of Various Ways to Fill an Array
require 'benchmark'
def bench
Benchmark.measure do
1_000_000.times { yield }
end.real
end
array = Array.new 10
bench { array.fill 'x' }
# => 0.277697
bench { array.map { 'x' } }
# => 2.398355
bench { array.map! { 'x' } }
# => 2.016466
bench { ['x'] * array.size }
# => 0.787285
bench { Array.new array.size { 'x' } }
# => 0.542437
RUBY_VERSION
# => "2.0.0"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment