简体   繁体   English

如何在Java中为“ new Integer(1)”分配内存?

[英]How is memory allocated for “new Integer(1)” in Java?

I am little bit confused with java's memory allocation technique. 我对Java的内存分配技术有些困惑。 Can anybody help me, how java will allocate memory for following code ? 有人可以帮我吗,java将如何为以下代码分配内存?

Integer a;
a = new Integer(1);

I am asking that for Integer a , jvm will create 64 bit reference and a = new Integer(1) for that it will allocate more memory to store value of 1. Is this correct ? 我要问的是, Integer a ,jvm将创建64位引用,而a = new Integer(1)将为其分配更多的内存来存储值1。这是正确的吗?

Integer a; will allocate memory in stack to hold the reference value and initialized with null 将在堆栈中分配内存以保存参考值并初始化为null

new creates instance in heap memory new在堆内存中创建实例

Most JVMs (even 64-bit ones) use 32-bit references. 大多数JVM(甚至是64位JVM)都使用32位引用。 (Newer JVMs uses 32-bit references for heaps up to almost 32 GB) The reference is on the stack or in a CPU register and is not usually counted. (较新的JVM将32位引用用于最大32 GB的堆)。该引用位于堆栈或CPU寄存器中,通常不计入。 The Integer is allocated on the heap. 整数在堆上分配。

Integer i = new Integer(1); // creates a new object every time.
Integer j = 1; // use a cached value.

Using auto boxing is not only shorter, but can be more efficient as it can use a cache. 使用自动装箱不仅更短,而且可以使用缓存,因此效率更高。

Of course the most efficient is 当然,最有效的是

int k = 1; // not object created and no heap used.

For autoboxed values the performance difference is very small compared with primitives and the reference is likely to be the same size as the int value. 对于自动装箱的值,与基元相比,性能差异非常小,并且引用的大小可能与int值相同。 However for larger values, there can be a significant performance difference. 但是,对于较大的值,可能会有明显的性能差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM