Created
March 15, 2023 19:45
-
-
Save tinogomes/112330d2116dc5b376894fed3e8bceae to your computer and use it in GitHub Desktop.
Benchmark to create an array on Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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