I did small performance test of Ruby\'s array concat()
vs +
operation and concat()
was way too fast.
I however am not clear on why
The OP's question, as noted in other answers, is comparing two operators that perform different purposes. One, concat
, which is destructive to (mutates) the original array, and +
which is non-destructive (pure functional, no mutation).
I came here looking for a more comparable test, not realizing at the time, that concat was destructive. In case it's useful to others looking to compare two purely functional, non-destructive operations, here is a benchmark of array addition (array1 + array2
) vs array expansion ([*array1, *array2]
). Both, as far as I'm aware, result in 3 arrays being created: 2 input arrays, 1 new resulting array.
Hint: +
wins.
Code
# a1 is a function producing a random array to avoid caching
a1 = ->(){ [rand(10)] }
a2 = [1,2,3]
n = 10_000_000
Benchmark.bm do |b|
b.report('expand'){ n.times{ [*a1[], *a2] } }
b.report('add'){ n.times{ a1[]+a2 } }
end
Result
user system total real
expand 9.970000 0.170000 10.140000 ( 10.151718)
add 7.760000 0.020000 7.780000 ( 7.792146)