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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With