Probably I won't give You the full answer, but for starters check implementation of Array#+
in C:
VALUE rb_ary_plus(VALUE x, VALUE y)
{
VALUE z;
long len;
y = to_ary(y);
len = RARRAY_LEN(x) + RARRAY_LEN(y);
z = rb_ary_new2(len);
MEMCPY(RARRAY_PTR(z), RARRAY_PTR(x), VALUE, RARRAY_LEN(x));
MEMCPY(RARRAY_PTR(z) + RARRAY_LEN(x), RARRAY_PTR(y), VALUE, RARRAY_LEN(y));
ARY_SET_LEN(z, len);
return z;
}
As You can see it defines new instance, copies over array X, then it copies array Y.
MEMCPY
is a macro, that should wrap memcpy()
. As this answer suggests C's memcpy
is O(N) - How do realloc and memcpy work?
So in our case it will be ~O(N+M). I suggest You to further examine Ruby source code. It's quite probable that in case of +=
it performs only single memcpy
. Also we have different implementations of Ruby.