Tuesday, September 09, 2014

(Java) Memory Usage


Some quick information on (Java) memory usage:

2^10 -> 1024 bytes = 1 KB
2^20 -> ~1 Million bytes = 1 MB
2^30 -> ~1 Billion bytes = 1 GB
2^32 -> ~4 Billion bytes = 4 GB
2^40 -> 100 GB = 1 TB

32 bits Machines --> 4 bytes pointers
64 bits Machines --> 8 bytes pointers (can address more memory, pointers use more space) (some VMs can compress these pointer to 4 bytes pointers)


Primitive types
-----------------------
boolean --> 1 byte
char       --> 2 bytes
short      --> 2 bytes
int          --> 4 bytes
float       --> 4 bytes
long       --> 8 bytes
double    --> 8 bytes

Array of primitive types
-------------------------------
char[]  --> 2N + 24
int[]  --> 4N + 24
double[] -->  8N + 24

char[][] ~2 MN
int [][] ~ 4 MN
double ~ 8 MN

Typical memory for object
-----------------------------------
* Object overhead -> 16 bytes
* Reference -> 8 bytes
* Padding (each object uses a multiple of 8 bytes)
* Inner class -> 8 bytes ( for pointer to enclosing class)

Example 01:
public Date {           --> 16 bytes (object overhead)
    private int year;   --> 4 bytes
    private month;     --> 4 bytes
    private day;          --> 4 bytes                      
}
                                  ----------------
                                   28 bytes
                                 + 4 bytes (padding)
                                 ---------------------
Total:                           32 bytes


Example 02:

public String {                          --> 16 bytes (object overhead)
      private char[]  value;          --> 8 bytes (reference) + (2N + 24)
      private int offset;                --> 4 bytes
      private int count;                --> 4 bytes
      private int hash;                  --> 4 bytes
}
                                                   ------------------
                                                      2N + 60 bytes
                                                      + 4 bytes (padding)
                                                     --------------------
                                                      2N + 64 bytes