Memory Requirements for a Program
Fun Fact: There is contention on the number of bits in a megabyte and gigabyte. Computer Scientists believe that there is bytes in a megabyte and bytes in a gigabyte, whereas the national institute of standards and technology defines a megabyte as 1 million bytes and a gigabyte as 1 billion bytes.
Typical memory usage for primitive types and arrays (Java)
Section titled “Typical memory usage for primitive types and arrays (Java)”Primitive Types
type | bytes |
---|---|
boolean | 1 |
byte | 1 |
char | 2 |
int | 4 |
float | 4 |
long | 8 |
double | 8 |
One dimensional arrays |
type | bytes |
---|---|
char[] | |
int[] | |
double[] | |
Two dimensional array |
type | bytes |
---|---|
char[][] | ~ |
int[][] | ~ |
double[][] | ~ |
Typical memory usage for objects in Java
Section titled “Typical memory usage for objects in Java”- Object overhead 16 bytes
- Reference 8 bytes
- Padding 8 bytes Total 32 bytes
Date Object represented by 32 bytes
String Object represented by bytes
Summarising Memory Usage
Section titled “Summarising Memory Usage”Once we understand the nature of our program and what’s required we calculate our total memory by taking into account.
- Total primitive types and bytes used
- Object references (8 bytes per reference)
- Arrays: 24 Bytes + memory for each array entry
- Objects: 16 Bytes + memory for each instance variable + 8 bytes if inner class (for pointer to enclosing class)
- Padding: round up to multiple of 8 bytes.
Real example
Section titled “Real example”Q. How much memory does our WeightedQuickUnionUF
class use asa function of N? (Tilde notation)
public class WeightedQuickUnionUF { private int[] id; private int[] sz; private int count;
public WeightedQuickUnionUF(int N) { id = new int[N]; sz = new int[N]; for (int i = 0; i < N; i++) id[i] = i; for (int i = 0; i < N; i++) sz[i] = 1; } ...}
My Answer / Working
- Object
WeightedQuickUnionUF
= 16 bytes - each
private
is a reference thereforeprivate int[] id
=private int[] sz
=private int count
=
- padding = 4
Largest constant = 8N
Answer = ~8N