英文:
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即使在存储byte
、short
(以及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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论