簡體   English   中英

NoMemoryError:無法使用BigDecimal .to_s方法分配內存

[英]NoMemoryError: failed to allocate memory using BigDecimal .to_s method

我使用Ruby 2.2.3Rails 4.2.3 我收到一個NoMemoryError: failed to allocate memoryirb控制台中使用以下代碼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

內存不足的事實並不奇怪。 數字123e+1000000000000000000具有一個五億個零。 將其表示為字符串將需要五百億個字符。

每字符一個字節,您正在(大約)查看10^18字節, 10^15 KB, 10^12兆字節或10^9千兆字節。 因此,除非您擁有十億千兆字節的RAM,否則它將無法正常工作。

一旦傳遞給BigDecimal構造函數的數字超過了系統上可以表示的最大數字,它將溢出到常數BigDecimal::INFINITY ,將其轉換為字符串后,它就是Infinity ,並且可以明顯地容納在內存中:

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

為什么不將其轉換為浮點數? 這對我有用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM