Ruby,不可变整数和未使用的对象

标签 ruby integer immutability

a = 1
a += 1
=> 2

原来的对象 1 现在没有被使用,这不是很实用。为什么整数在 ruby 中是不可变的?我查看了stackoverflow,但找不到任何解释。

最佳答案

整数和所有Numerics , 是不可变的,所以每一个都只有一个。我们可以通过查看他们的#object_id 来了解这一点。 .

2.6.4 :001 > a = 1
 => 1 
2.6.4 :002 > a.object_id
 => 3 
2.6.4 :003 > 1.object_id
 => 3 
2.6.4 :004 > b = 1
 => 1 
2.6.4 :005 > b.object_id
 => 3 

此行为也记录在 Numeric 中。

Other core numeric classes [other than Numeric] such as Integer are implemented as immediates, which means that each Integer is a single immutable object which is always passed by value. There can only ever be one instance of the integer 1, for example. Ruby ensures this by preventing instantiation. If duplication is attempted, the same instance is returned.

为每个 Integer 设置一个不可变对象(immutable对象)可以在正常使用时节省内存,您将大量使用 1。每个人共享相同的 1 可以节省大量内存,但这意味着它必须是不可变的,否则添加到一个对象会改变其他对象,that would be bad .

不必不断地解除分配和一遍又一遍地分配相同的 Integer 更快并减少内存碎片。如果真的没用,Ruby will garbage collect them . Ruby 的垃圾收集功能在不断改进,并且可以通过许多环境变量进行调整。

它还简化了它们的实现并提高了它们的性能。不可变对象(immutable对象)可以缓存任何计算,确信缓存永远不需要失效。

关于Ruby,不可变整数和未使用的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63537342/

相关文章:

ruby - 如何从 DataMapper::Collection 获取原始 SQL?

ruby - 无法安装 Curb - native 扩展有问题。

ruby-on-rails - 找不到有效的 gem 安装 activerecord-sqlite3-adapter

sql - 使用 created_at 选择记录范围

oop - 我可以在不知道其上下文的情况下更新深层嵌套的不可变对象(immutable对象)吗?

c++ - C++ 标准是否要求有符号整数只有一个符号位?

Haskell 将整数转换为 Int?

integer - 仅使用整数求平方根

javascript - 使用不变性助手更新 React 状态下的数组对象

arrays - Swift 中带有数组的 For-In 循环中迭代器元素的可变性