在Java中转换基本数据类型,JVM会尝试节省内存吗?

huangapple go评论77阅读模式
英文:

Casting java primitives, does the JVM try to save memory?

问题

var foo = (short) 40 + (byte) 10;

foo占用多少字节?
它的类型是什么?

我预期结果会存储在short中,但为了节省内存,JVM会测试以查看是否适合更小的原始类型吗?

如果是(short) 1 + (byte) 1,它仍然是short吗?

英文:
var foo = (short) 40 + (byte) 10

How many bytes does foo take up?
What is its type?

I would expect that the result is stored in a short, but to save memory does the JVM test to see if it will fit in a smaller primitive?

If it were (short) 1 + (byte) 1 would it still be a short?

答案1

得分: 4

经验法则:如果其中一个参数是long,整数算术运算会被视为long,并且结果也是long,否则为int

我还怀疑JVM即使在存储byteshort(以及boolean)变量时也会使用4字节 - 请参阅JVMS 2.6.1. 本地变量表2.11.1-B


甚至
var test = (byte)1 + (byte)1
都会导致test是一个int

但对于var test = (byte)(1 + 1),情况不同。

英文:

Rule of thumb: integer arithmetic operations are done as long and result in long if either argument is long, int otherwise.

I also suspect that the JVM uses 4 bytes even to store byte and short (and boolean) variables - see JVMS 2.6.1. Local Variables and Table 2.11.1-B.


Even
var test = (byte)1 + (byte)1
will cause test to be an int.

Not the case for var test = (byte)(1 + 1)

huangapple
  • 本文由 发表于 2020年8月26日 04:12:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63586417.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定