Always returns a new list from a function or not?

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?

+4
source share
4

. (- , , , ).

. , . , , , GC .

, , . , . , , , . , , .

, , , .

+12

. , . , , - , , . .

, , , , , / , .

+4

. .

, , , .

+1

, 1. , @BartoszKP, , , IEnumerable. , . :

public IEnumerable<employee> GetItems()
{
  return new List<employee> { 
    new employee("Alan"),
    new employee("Bob"),  
    new employee("Carla")
  }; 
}
0

Source: https://habr.com/ru/post/1607305/


All Articles