Array#+
vs Array#concat
@dezmo and I were privately discussing the benefits and speed of Array#+
versus using Array#concat
.
Backstory ...
The impetus for the tests came from the comparison of …
def get_instances(ents)
ents.grep(Sketchup::Group) + ents.grep(Sketchup::ComponentInstance)
end
… which creates a new 3rd array, … to the following which does not create a 3rd array:
def get_instances(ents)
ents.grep(Sketchup::Group).concat(ents.grep(Sketchup::ComponentInstance))
end
The results of the test pleasantly surpassed expectations, so I thought I would share the results.
The test code:
GC.start
a2 = ["text"]
a1 = []
t = Time.now
100000.times{
a1 += a2
}
t1 = Time.now
puts "Array+: #{t1-t} secs"
b1 = []
t = Time.now
100000.times{
b1.concat(a2)
}
t1 = Time.now
puts "Concat: #{t1-t} secs"
Results: (on my i7-8750H CPU @ 2.20GHz machine)
Array+: 6.3678292
Concat: 0.0107127
The first time I ran it (on my machine,) Array#+
was 9.8 secs! It seems to be much longer the first time it is run, but afterward quickly settles down into an average from 5.1-5.8 secs.
Array#concat
is between at 0.0103-0.0107 secs. (Yes that is 1 hundredth of a second!)
Conclusion:
Array#+
is a minimum of 500 times slower than Array#concat
!
BUT WAIT ! It gets better …
I then made the a2
array much more complex with multiple members of various types, ie …
a2 = ["text",1,Math::PI,{:key =>"value"},:symbolic]
… and reran the test. The results were even more surprising:
Array+: 56.0732861 secs
Concat: 0.0175667 secs
So array addition took almost a full minute.
… but array concatenation was still under 2 hundredths of a second!
That’s like 3200 times faster. And that’s crazy good.