NoMemoryError: failed to allocate memory using BigDecimal .to_s method

NoMemoryError: failed to allocate memory using BigDecimal .to_s method

我使用 Ruby 2.2.3Rails 4.2.3。我在 irb 控制台中使用以下代码得到一个 NoMemoryError: failed to allocate memory

# Using 123e+1000000000000000000
BigDecimal('123e+1000000000000000000').to_s
#=> NoMemoryError: failed to allocate memory

但是这个数字更大的例子是可行的:

# Using 123e+1000000000000000000000000000000000
BigDecimal('123e+1000000000000000000000000000000000').to_s
#=> "Infinity"

这里是BigDecimal的代码:https://github.com/rails/rails/blob/v4.2.3/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb

为什么不将其转换为浮点数?这对我有用:

BigDecimal('123e+1000000000000000000').to_f
=> Infinity

您 运行 内存不足这一事实并不奇怪。数字 123e+1000000000000000000 有 quintillion 个零。将其表示为字符串将需要 quintillion 个字符。

每个字符一个字节,您正在查看(大致)10^18 字节、10^15 千字节、10^12 兆字节或 10^9 千兆字节。因此,除非您拥有 10 亿千兆字节的 RAM,否则它不会很好地工作。

一旦传递给 BigDecimal 构造函数的数字超过了系统上可以表示的最大数字,它将溢出到常量 BigDecimal::INFINITY,当转换为字符串时,它只是Infinity,并且可以清楚地放入内存中:

BigDecimal('123e+1000000000000000000000000000000000') == BigDecimal::INFINITY
#=> true