Forum: Ruby array.concat(a) vs array.push(*a)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
unknown (Guest)
on 2006-04-24 14:45
(Received via mailing list)
It feels to me like array.concat seems slower than the equivalent (I
think) variation using array.push:

>> a = [1,2,3,4,5]; b=[]; puts Benchmark.measure{ (1..100000).each{ b.push(*a)}}
   0.090000   0.000000   0.090000 (  0.090436)

>> a = [1,2,3,4,5]; b=[]; puts Benchmark.measure{ (1..100000).each{ b.concat(a)}}
   0.290000   0.000000   0.290000 (  0.296501)

(using ruby 1.8.4)

This surprised me somewhat, because earlier
(http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/...)
it was suggested that concat is a fast way of appending to arrays.


Is there something I'm missing, or does it seem I should be
using push(*a) in places where I had been using concat(a)?
unknown (Guest)
on 2006-04-24 14:55
(Received via mailing list)
Hmm... perhaps answering my own question ....
array.push(*a) segfaults more than concat does....

> > a = [1,2,3,4,5]; puts Benchmark.measure{ (1..20).each{ a.concat(a)}}
   0.100000   0.040000   0.140000 (  0.143773)
=> nil
> > a = [1,2,3,4,5]; puts Benchmark.measure{ (1..20).each{ a.push(*a)}}
Segmentation fault
Robert D. (Guest)
on 2006-04-24 14:58
(Received via mailing list)
On 4/24/06, removed_email_address@domain.invalid <
removed_email_address@domain.invalid> wrote:
> >> a = [1,2,3,4,5]; b=[]; puts Benchmark.measure{ (1..100000).each{
> Is there something I'm missing, or does it seem I should be
> using push(*a) in places where I had been using concat(a)?
>
>
Very interesting, as a matter concat is faster - as shown below- under
*normal* circumstances
obviously push is faster for very very long receivers.
Can somebody explain why, I could study the code, but I am not sure I
would
find it even if I had the time.
Cheers
cat array.rb; ruby array.rb
require 'benchmark'
a = [1,2,3,4,5]; puts Benchmark.measure{ (1..1000000).each{
b=[];b.push(*a)}}
a = [1,2,3,4,5]; puts Benchmark.measure{ (1..1000000).each{ b=[];
b.concat
(a)}}
  2.320000   0.000000   2.320000 (  2.938714)
  1.980000   0.000000   1.980000 (  2.301109)

Robert


--
Deux choses sont infinies : l'univers et la bêtise humaine ; en ce qui
concerne l'univers, je n'en ai pas acquis la certitude absolue.

- Albert Einstein
This topic is locked and can not be replied to.