user1329714
user1329714

Reputation: 1

manage memory for memorystream

Which is better for Memory ? Which is lower in memory consumption?

byte[] Pic = (byte[])re.GetValue(4);
MemoryStream MS = new MemoryStream();
MS.Write(Pic, 0, Pic.Length);
pictureBox1.BackgroundImage = Image.FromStream(MS);

or

pictureBox1.BackgroundImage = Image.FromStream(new MemoryStream((byte[])re.GetValue(4), true));

Upvotes: 0

Views: 560

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

Second one will work faster and it will use less memory. When you initialize MemoryStream from constructor, bytes simply assigned to inner buffer (stream will be non-resizable):

public MemoryStream(byte[] buffer, bool writable)
{    
    _buffer = buffer;    
    _writable = writable;
    _exposable = false;
}

If you use parameterless constructor, stream will be resizable with initial capacity 0. During writing new byte array will be created and values will be copied to internal buffer:

public MemoryStream()
{    
    _buffer = new byte[0];   
    _writable = true;
    _exposable = true;
}

public override void Write(byte[] buffer, int offset, int count)
{
    // EnsureCapacity
    byte[] dst = new byte[_position + count];
    Buffer.InternalBlockCopy(_buffer, 0, dst, 0, _length);
    _buffer = dst;
    // Copy
    Buffer.InternalBlockCopy(buffer, offset, _buffer, _position, count);
}

Upvotes: 2

Related Questions