Java Memory Usage

来源:互联网 发布:必向东java 编辑:程序博客网 时间:2024/05/20 03:07

eg:

1.5.4The correct answer is: 944public class MysteryBox {                     //   16 (object overhead)    private long x0;                          //    8 (1 long)    private double y0, y1;                    //   16 (2 double)    private boolean z0, z1;                   //    2 (2 boolean)    private int[] a = new int[216];           //    8 (reference to array)                                              //  888 (int array of size 216)    ...                                             6 (padding to round up to a multiple of 8)}                                                ----                                                  944

(The explanation below is copied from http://algs4.cs.princeton.edu/11model/)

Memory usage.

 To estimate how much memory our program uses, we can count up the number of variables and weight them by the number of bytes according to their type. For a typical 64-bit machine,
  • Primitive types. the following table gives the memory requirements for primitive types.

    memory requirements for primitive types
  • Objects. To determine the memory usage of an object, we add the amount of memory used by each instance variable to the overhead associated with each object, typically 16 bytes. Moreover, the memory usage is typically padded to be a multiple of 8 bytes (on a 64-bit machine).

    memory requirement of Integer memory requirement of Date
  • References. A reference to an object typically is a memory address and thus uses 8 bytes of memory (on a 64-bit machine).
  • Linked lists. A nested non-static (inner) class such as our Node class requires an extra 8 bytes of overhead (for a reference to the enclosing instance).

    memory requirement of Node
  • Arrays. Arrays in Java are implemented as objects, typically with extra overhead for the length. An array of primitive-type values typically requires 24 bytes of header information (16 bytes of object overhead, 4 bytes for the length, and 4 bytes of padding) plus the memory needed to store the values.

    memory requirement of arrays
  • Strings. A String of length N typically uses 40 bytes (for the String object) plus 24 + 2N bytes (for the array that contains the characters) for a total of 64 + 2N bytes.

    memory requirement of String
    Beginning with Oracle and OpenJDK Java 7, Update 6, the representation of the string data type has changed. See this article for more details.


0 0
原创粉丝点击