Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return always new list from a function or not?

Tags:

c#

.net

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:

  1. initialize always new list inside this function, add items to it and return this list or;
  2. have a list stored in a field, clear items from it, add new items and return this list

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?

like image 239
Nuts Avatar asked Dec 02 '22 16:12

Nuts


1 Answers

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.

like image 77
BradleyDotNET Avatar answered Dec 15 '22 02:12

BradleyDotNET