Ruby Array concat versus + speed?

后端 未结 2 1929
谎友^
谎友^ 2021-02-12 06:09

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

相关标签:
2条回答
  • 2021-02-12 06:36

    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.

    0 讨论(0)
  • 2021-02-12 06:48

    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.

    0 讨论(0)
提交回复
热议问题