Ruby Array concat versus + speed?

arrays, performance, ruby

Solution

According to the Ruby docs, the difference is:

Array#+ :

Concatenation — Returns a new array built by concatenating the two arrays together to produce a third array.

Array#concat :

Array#concat : Appends the elements of other_ary to self.

So the `+` operator will create a new array each time it is called (which is expensive), while `concat` only appends the new element.

Problem

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 `concat()` is so fast? Can anyone help here? This is the code I used: ``` t = Time.now ar = [] for i in 1..10000 ar = ar + [4,5] end puts "Time for + " + (Time.now - t).to_s t = Time.now ar = [] for i in 1..10000 ar.concat([4,5]) end puts "Time for concat " + (Time.now - t).to_s ```

Original source