Ruby Array concat versus + speed?

后端 未结 4 541
萌比男神i
萌比男神i 2021-02-12 06:00

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

4条回答
  •  感动是毒
    2021-02-12 06:49

    The answer lies in Ruby's underlying C implementation of the + operator and the concat methods.

    Array#+

    rb_ary_plus(VALUE x, VALUE y)
    {
        VALUE z;
        long len, xlen, ylen;
    
        y = to_ary(y);
        xlen = RARRAY_LEN(x);
        ylen = RARRAY_LEN(y);
        len = xlen + ylen;
        z = rb_ary_new2(len);
    
        ary_memcpy(z, 0, xlen, RARRAY_CONST_PTR(x));
        ary_memcpy(z, xlen, ylen, RARRAY_CONST_PTR(y));
        ARY_SET_LEN(z, len);
        return z;
    }
    

    Array#concat

    rb_ary_concat(VALUE x, VALUE y)
    {
        rb_ary_modify_check(x);
        y = to_ary(y);
        if (RARRAY_LEN(y) > 0) {
            rb_ary_splice(x, RARRAY_LEN(x), 0, y);
        }
        return x;
    }
    

    As you can see, the + operator is copying the memory from each array, then creating and returning a third array with the contents of both. The concat method is simply splicing the new array into the original one.

提交回复
热议问题