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
If you're going to run benchmarks, take advantage of prebuilt tools and reduce the test to the minimum necessary to test what you want to know.
Starting with Fruity, which provides a lot of intelligence to its benchmarking:
require 'fruity'
compare do
plus { [] + [4, 5] }
concat { [].concat([4, 5]) }
end
# >> Running each test 32768 times. Test will take about 1 second.
# >> plus is similar to concat
When things are close enough to not really worry about, Fruity will tell us they're "similar".
At that point Ruby's built-in Benchmark class can help:
require 'benchmark'
N = 10_000_000
3.times do
Benchmark.bm do |b|
b.report('plus') { N.times { [] + [4, 5] }}
b.report('concat') { N.times { [].concat([4,5]) }}
end
end
# >> user system total real
# >> plus 1.610000 0.000000 1.610000 ( 1.604636)
# >> concat 1.660000 0.000000 1.660000 ( 1.668227)
# >> user system total real
# >> plus 1.600000 0.000000 1.600000 ( 1.598551)
# >> concat 1.690000 0.000000 1.690000 ( 1.682336)
# >> user system total real
# >> plus 1.590000 0.000000 1.590000 ( 1.593757)
# >> concat 1.680000 0.000000 1.680000 ( 1.684128)
Notice the different times. Running a test once can result in misleading results, so run them several times. Also, make sure your loops result in a time that isn't buried in background noise caused by processes kicking off.