Why did Matz choose to make Strings mutable by default in Ruby?

后端 未结 2 514
情歌与酒
情歌与酒 2020-12-05 03:55

It\'s the reverse of this question: Why can't strings be mutable in Java and .NET?

Was this choice made in Ruby only because operations (appends and such) are ef

2条回答
  •  隐瞒了意图╮
    2020-12-05 04:41

    This is in line with Ruby's design, as you note. Immutable strings are more efficient than mutable strings - less copying, as strings are re-used - but make work harder for the programmer. It is intuitive to see strings as mutable - you can concatenate them together. To deal with this, Java silently translates concatenation (via +) of two strings into the use of a StringBuffer object, and I'm sure there are other such hacks. Ruby chooses instead to make strings mutable by default at the expense of performance.

    Ruby also has a number of destructive methods such as String#upcase! that rely on strings being mutable.

    Another possible reason is that Ruby is inspired by Perl, and Perl happens to use mutable strings.

    Ruby has Symbols and frozen Strings, both are immutable. As an added bonus, symbols are guaranteed to be unique per possible string value.

提交回复
热议问题