Skip to content

Instantly share code, notes, and snippets.

@fractaledmind
Created October 9, 2024 17:05
Show Gist options
  • Save fractaledmind/792f5b91aa9b10d0436ccfe26f7d4fd8 to your computer and use it in GitHub Desktop.
Save fractaledmind/792f5b91aa9b10d0436ccfe26f7d4fd8 to your computer and use it in GitHub Desktop.
Ruby benchmark script to test which way is faster to merge two arrays: Array + Array or Array << Entry
require 'benchmark'
def array_plus_array(n)
result = []
n.times do |i|
result = result + [i]
end
result
end
def array_shovel(n)
result = []
n.times do |i|
result << i
end
result
end
def run_benchmark(n)
Benchmark.bm(15) do |x|
x.report("Array + Array:") { array_plus_array(n) }
x.report("Array << Entry:") { array_shovel(n) }
end
end
puts "Benchmark for small arrays (100 elements):"
run_benchmark(100)
puts "\nBenchmark for medium arrays (10,000 elements):"
run_benchmark(10_000)
puts "\nBenchmark for large arrays (100,000 elements):"
run_benchmark(100_000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment