Skip to content

Instantly share code, notes, and snippets.

@tinogomes
Created March 15, 2023 19:45
Show Gist options
  • Save tinogomes/112330d2116dc5b376894fed3e8bceae to your computer and use it in GitHub Desktop.
Save tinogomes/112330d2116dc5b376894fed3e8bceae to your computer and use it in GitHub Desktop.
Benchmark to create an array on Ruby
require "rubygems"
require "benchmark"
def run
text = 'HEADER'
n = 30
n_times = 1_000_000
base = [text]
range = (1..30)
header = ['REC_TYPE']
Benchmark.bm(16) do |x|
x.report("Array.new") { n_times.times { header + Array.new(n, text) } }
x.report("[] * n") { n_times.times { header + base * n } }
x.report("map") { n_times.times { header + range.map { text } } }
end
nil
end
run
puts "type 'run' to execute the benchmark"
__END__
user system total real
Array.new 0.262522 0.094536 0.357058 ( 0.379042)
[] * n 0.300455 0.049564 0.350019 ( 0.356919)
map 1.564741 0.047170 1.611911 ( 1.612839)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment