Java BigDecimal 内存使用情况?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2501176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 21:30:42  来源:igfitidea点击:

Java BigDecimal memory usage?

javamemorymemory-managementbigdecimal

提问by Marcus Leon

Is there a guideline for estimating the amount of memory consumed by a BigDecimal?

是否有用于估计 a 消耗的内存量的指南BigDecimal

Looking for something similar to these guidelinesfor estimating Stringmemory usage.

寻找类似于这些用于估计内存使用情况的指南String

回答by M. Jessup

If you look at the fields in the source for BigDecimalthere is:

如果您查看源中的字段,则BigDecimal有:

BigDecimal:
  long intCompact +8 bytes
  int precision +4 bytes
  int scale +4 bytes
  String stringCache +?
  BigInteger intVal +?

BigInteger:
  int bitCount +4 bytes
  int bitLength +4 bytes
  int firstNonzeroIntNum +4 bytes
  int lowestSetBit +4 bytes
  int signum +4 bytes
  int[] mag +?

The comment for stringCachesays

评论stringCache

Used to store the canonical string representation, if computed.

用于存储规范字符串表示(如果已计算)。

Assuming you don't call .toString(), it will remain zero bytes. Hence BigDecimalis (8+4+4)=16 bytes + BigInteger.

假设您不调用.toString(),它将保持零字节。因此BigDecimal是 (8+4+4)=16 bytes + BigInteger

BigIntegeritself is 4+4+4+4+4=20 bytes + mag.

BigInteger本身是 4+4+4+4+4=20 bytes + mag

20+16 gives total of 36 bytes plus the magnitude, which is always the minimum number of bits necessary to represent the full integer. For a number nit will need log2(n)bits, which can be converted to ints. You should be using about:

20+16 总共有 36 个字节加上幅度,这始终是表示完整整数所需的最小位数。对于一个数字,n它需要log2(n)位,可以转换为整数。你应该使用关于:

36 + Ceiling(log2(n)/8.0) bytes

(note this doesn't include any of the other object descriptor overhead as your example link for strings does, but it should give you a good general idea.)

(请注意,这不包括任何其他对象描述符开销,如您的字符串示例链接所做的那样,但它应该给您一个很好的总体思路。)

回答by Adamski

If you dig into the internals of BigDecimalyou'll see that it uses a compact representation if the significand is <= Long.MAX_VALUE. Hence, the memory usage can vary depending on the actual values you're representing.

如果您深入研究内部结构,BigDecimal您会发现如果有效数是 <= 则它使用紧凑表示Long.MAX_VALUE。因此,内存使用量可能会因您所代表的实际值而异。