Chris
Chris

Reputation: 4370

Memory overhead when adding an object to a List directly vs. object creation

Is there a memory overhead when creating a Java object first, instead of adding it directly to a List or will the List automatically use the memory from the object, which is already allocated?

User user = new User(userID, username);
userList.add(user);

vs.

userList.add(new User(userID, username));

Upvotes: 1

Views: 116

Answers (5)

Sumit Kumar
Sumit Kumar

Reputation: 395

  1. There will not be any memory overhead as reference will be stored on stack.
  2. But there will be negligible performance penalty of creating extra reference variable which will be observed in case if someone tries to create it inside the for loop for very high value of n.

     List<User> users = new ArrayList<>(size);
            for (int i = 0; i < n; i++) {
                User user = new User("User " + i, i);
                users.add(user);
            }
    

Upvotes: 0

snakile
snakile

Reputation: 54521

There's no memory overhead. The extra reference to the list element (the user variable) resides on the stack. The first element of the list and the user variable reference the same object on the heap. In both cases there's a single memory allocation.

Upvotes: 3

Kayaman
Kayaman

Reputation: 73558

The object is not added to the list in either case. A reference to the object is added. The difference is only whether you intend to do something else with the object after adding it to the list. In the first case you still have the user variable referring to the object, so you can easily manipulate it further. In the latter case you don't have the variable, presumably you don't need to manipulate it anymore.

Upvotes: 0

davidxxx
davidxxx

Reputation: 131376

It's broadly the same thing. The memory allocation is done a single time in both cases.

The difference is that :
- in the first case, two references use the object.
- In the second case, one reference uses the object.

Upvotes: 1

Mark
Mark

Reputation: 1498

User user = new User(userID, username);

This line actually does two things. First it creates an object in memory (that's the right side of the =). After that, it creates a new variable called user and stores a reference to newly created object in it.

If you add it to the list then, the list will simply create another reference to the created object.

So in both cases, the object is only created once.

However, in the first case, you will create an additional variable (user). It's a reference though and not the object itself, so the memory it actually takes is basically nothing. And it's gone once the method you did this in finished anyway.

Upvotes: 1

Related Questions