'which is better in terms of performance?

List empList = new ArrayList<>();

    for(int i=0; i<1000; i++)
{
empList = getEmployeeList(empId);

or
empList.clear();
empList.addAll(getEmployeeList(empId));
}

if they are equal which is better in terms of memory and performance ?



Solution 1:[1]

No, these do two different things.

The first one takes the result of a function and assigns the variable empList to be a reference to that return value. That means the value of empList changes. The second one takes the list returned by getEmployees and adds all the items to the existing list empList.

A few consequences of this difference:

  • If empList was not assigned a value, the second one would throw a NullPointerException.
  • If empList already had items in it, the first would lose those values. The second would retain them and place the new items after those original items.

As for performance- the first is always going to be higher perf, because its just a reference set whereas the second requires a call to addAll and whatever overhead it has (which may mean walking the list returned by getEmployees). The real answer for which you should use though is determined by whether you want to keep any data already in empList or not.

Edit: The question has since been edited changing it so one of my points is no longer quite true (it added a call to clear). With a call to clear that wouldn't cause it to save previous items. However the difference around unassigned/null would still be an issue. And the perf of the second would be much worse, as you now have 2 function calls and associated overhead.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1