Heap and stack differences "take Java as an example to dive into the analysis"

Source: Internet
Author: User

The Java heap is a run-time data area where the objects of the class are allocated space, which are established through directives such as new. Heap is responsible for garbage collection, the advantage of the heap is the ability to dynamically allocate memory size, the lifetime does not have to tell the compiler beforehand, the Java garbage collector will automatically take away the data that is no longer used. However, the disadvantage is that the access speed is slower due to the dynamic allocation of memory at run time. " the advantage of the stack is that the access speed is faster than the heap, after the register, the stack data can be shared. However, the disadvantage is that the size and lifetime of the data in the stack must be deterministic and inflexible. The stack mainly contains some basic types of variables (, int, short, long, byte, float, double, Boolean, char) and object handle.

1.heap is a heap and stack is a stack.

2.stack of space is automatically allocated and freed by the operating system, and heap space is manually applied and released, and the heap is commonly assigned with the New keyword.

3.stack space is limited, and the heap space is a large free zone.

In Java,

If you just declare an object, assign it to the address space in the stack memory first.

If you instantiate it again, it will be assigned an address in heap memory.

4. For example:

Data type variable name; This defines something in the stack area.

such as: Object a =null; Allocate space only in stack memory

New data type (), or malloc (length); That's what defines it in the heap area.

such as: Object B =new Object (); Allocates space in heap memory

Heap and stack differences "take Java as an example to dive into the analysis"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.