In C#, does the following save any memory?
private List<byte[]> _stream;
public object Stream
{
get
{
if (_stream == null)
{
_stream = new List<byte[]>();
}
return _stream;
}
}
Edit: sorry, I guess I should have been more specific.
Specifically using “object” instead of List… I thought that would kinda clue itself in because it’s a weird thing to do.
It saves a very small amount of memory. The amount of memory an empty
List<byte[]>is going to take up is byte size.The reason why is that your reference variable
_streamonly needs to allocate enough memory to hold a reference to an object. Once an object is allocated, it will take up a certain amount of memory which may grow or shrink over time, such as when newbyte[]s are added to theList. However the memory taken up by the reference to that object will remain the same size.This is simpler and less prone to corner cases that cause you headaches:
Although, in most cases it’s not really optimal to be returning references to private members when they are collections/arrays, etc. Better to return
_stream.AsReadOnlyCollection().