nukeforum
nukeforum

Reputation: 1324

Actual memory impact of adding an item to a collection

When I put a 2MB object Foo bar into Collection<Foo>, are there now 4MB of Foos in memory or only 2MB?

e.g.

Foo twoMBObject = new Foo();
ArrayList<Foo> bax = new ArrayList<>();
bax.add(twoMBObject);

/* Do we now have bax-twoMBObject & twoMBObject or just twoMBObject 
and a pointer to twoMBObject in the list? */

Edit
I'm having a hard time figuring out if the suggested duplicate question is actually a duplicate. Although the accepted answer does not answer this question, one of the answers provided does. I'm not sure how to proceed here.

Upvotes: 1

Views: 73

Answers (2)

someone_somewhere
someone_somewhere

Reputation: 811

You have 2MB because you just add a reference to the object and do not create a copy of the object.

An easy way to test this is by using the Runtime.getRuntime().totalMemory() method. Example:

public static void main(String[] args) {
    Byte[] b = new Byte[1000];
    Runtime runtime = Runtime.getRuntime();

    long allocatedMemory = runtime.totalMemory() - runtime.freeMemory();
    System.out.println(allocatedMemory);

    List<Byte[]> collection = new ArrayList<>();
    collection.add(b);

    allocatedMemory = runtime.totalMemory() - runtime.freeMemory();
    System.out.println(allocatedMemory);
}

Upvotes: 4

Atri
Atri

Reputation: 5831

are there now 4MB of Foos in memory or only 2MB?

2 MB, because when you do new Foo(), 2MB of space is allocated and a reference to the object is returned. Now when you bax.add(twoMBObject); you are essentially adding the reference to the ArrayList and not creating a "new" object.

If you try to change something in the object using the reference twoMBObject you will see the change reflected in the object added to the ArrayList as well. This proves that its the same object.

Upvotes: 2

Related Questions