Reputation: 2813
I need to create a public function to a class where that function returns a List
of item, say List(of employee) for example.
This function will be called frequently from outside this class.
From the memory consumption point of view, is it better to:
A code example:
1.
public List<employee> GetItems()
{
List<employee> list = new List<employee>();
list.Add(new employee());
list.Add(new employee());
....
return list;
}
2.
private List<employee> _list = new List<employee>();
public List<employee> GetItems()
{
_list.Clear();
_list.Add(new employee());
_list.Add(new employee());
...
return _list;
}
Is one of the above more preferred in terms of memory consumption? And in what circumstances one of the above should be used instead of the other option?
Upvotes: 4
Views: 477
Reputation: 357
As many of the respondents stated, select choice 1. Also as @BartoszKP stated, I would probably return IEnumerable. You can save yourself a few keystrokes by shortcutting the initialization. You can express the code as follows:
public IEnumerable<employee> GetItems()
{
return new List<employee> {
new employee("Alan"),
new employee("Bob"),
new employee("Carla")
};
}
Upvotes: 0
Reputation: 46977
Never do option two. Remember that you are returning the same reference. So while you are clearing the list, someone else might for example be trying to iterate it. And that will cause exceptions.
Also after you have returned the list you can't control what others are doing to it, for example adding/removing items will effect all callers who got the list from the function.
Upvotes: 4
Reputation: 59035
Those two examples aren't equivalent. In the second example, you will be returning a reference to the same list.
The first method will always return a unique object, which is presumably what you want.
Upvotes: 1
Reputation: 61369
The second option will use less memory. Potentially a lot less (due to some behavior you may not have considered yet).
The first sample returns an actual new object to the caller. Since the local variable immediately goes out of scope, the lifetime of the object will be determined by the caller. So it will use more memory because more objects are created, and even if they are quickly destroyed, the GC won't collect them right away.
The second option only ever has the one object, and thus uses less memory. However this means that all callers will be pointing to the same object. So each time you clear and add, it effects all previous callers unless they made a copy. Additionally, a large threading hazard exists if multiple threads use this class.
The second option, while it uses less memory, is extremely dangerous code, and I would be very hesitant about using it.
Upvotes: 12