The in-place version, x << y
, is more memory efficient as the existing object is extended. This reduces pressure on the garbage collector.
The alternate, with either x = x + [ y ]
or x += [ y ]
is far less efficient, where you're creating an extremely short-lived temporary array, then appending that to a new array, then discarding the old array.
You should use in-place modifications unless one or more of the following conditions apply:
- The array should not be altered, as in it's an argument you don't "own"
- The array is frozen and cannot be altered
The differences get magnified depending on how many operations you're doing. If you're doing a lot of append operations it might make sense to accumulate those in an append buffer, the add them on all at once like:
y = [ ]
z.each do |a|
# Example with processing
y << a
end
x = x.concat(y)
Though these are highly situational.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…