1

Say I have an array a with length n, and I wish to add another another array b with length m. Namely

a+=b

What is the order of complexity for such operation? I know that in PERL, it has a buffer, so if m isn't large, it is ~ o(m). Let us us take two cases:
1. m << n
2. m ~ n
Thanks.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
user1134991
  • 3,003
  • 2
  • 25
  • 35

1 Answers1

1

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.

Community
  • 1
  • 1
Edgars Jekabsons
  • 2,833
  • 15
  • 20