Skip to content

Instantly share code, notes, and snippets.

@postmodern
Created August 1, 2022 00:45
Show Gist options
  • Save postmodern/83731685900fb851ee799026ba46e087 to your computer and use it in GitHub Desktop.
Save postmodern/83731685900fb851ee799026ba46e087 to your computer and use it in GitHub Desktop.
Micro-benchmark to test different ways of adding Arrays
#!/usr/bin/env ruby
require 'benchmark'
Benchmark.bm do |b|
n = 1_000_000
array1 = [1,2,3,4,5,6]
array2 = [7,8,9,10,11,12,13,14]
array3 = [15,16,17,18,19,20]
b.report('array + array + ...') do
n.times do
array1 + array2 + array3
end
end
b.report('[*array, *array, ...]') do
n.times do
[*array1, *array2, *array3]
end
end
end
user system total real
array + array + ... 0.223602 0.000000 0.223602 ( 0.225337)
[*array, *array, ...] 0.384585 0.005859 0.390444 ( 0.393595)
@samflores
Copy link

If in place update is a viable option you could also use concat:

  b.report('array.concat(array, ...)') do
    n.times do
      array1.concat(array2, array3)
    end
  end

  b.report('array.concat(array).concat(array)...') do
    n.times do
      array1.concat(array2).concat(array3)
    end
  end
array + array + ...  0.140634   0.001944   0.142578 (  0.142576)
[*array, *array, ...]  0.297938   0.000000   0.297938 (  0.297953)
array.concat(array, ...)  0.227805   0.018993   0.246798 (  0.246806)
array.concat(array).concat(array)...  0.145018   0.021008   0.166026 (  0.166041)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment