I need to create a public function for a class where this function returns an Listelement, such as List (employee).
This function will be called often from outside this class.
In terms of memory consumption is better:
- always initialize a new list inside this function, add elements to it and return this list or;
- have a list stored in a field, clear its elements, add new elements and return this list
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 preferable in terms of memory consumption? And in what circumstances should one of the above be used instead of the other option?
source
share