Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

immutability - What is gained by modifying a variable in place vs reassignment in Ruby?

In ruby, an array might be updated in one of the following ways:

original_array = []
original_array << 'first'

# or

original_array = []
original_array = original_array + ['first']

Are there advantages in the second form? I am asking as it "feels" immutable, but knowing the variable is simply reassigned has me thinking it offers nothing but a longer statement and uses a little more memory.

At the same time, experiences with immutability in other langues produces a negative reaction in me to array << 'something'.

Are there significant advantages to mutating a variable (array, hash, etc) in place in Ruby? Are there advantages to reassigning the same variable from an "immutable" operation? Is "immutability" even an appropriate concept with which to describe this?

question from:https://stackoverflow.com/questions/65928554/what-is-gained-by-modifying-a-variable-in-place-vs-reassignment-in-ruby

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...