想要重用MemoryStream

想要重用MemoryStream

本文介绍了想要重用MemoryStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码使用MemoryStream对网络中的对象进行序列化/反序列化.我想在课堂上重用一个MemoryStream,而不是每次需要时都创建一个新的MemoryStream.通过电线发送一些东西.

My code uses MemoryStream to serialize/deserialize objects to/from the network. I would like to re-use a single MemoryStream in my class, rather than create a new one each time I needto send something over the wire.

有人知道该怎么做吗?

代码段:

    // Serialize object to buffer
    public  byte[] Serialize(object value)
    {
        if (value == null)
            return null;
      MemoryStream _memoryStream = new MemoryStream();

        _memoryStream.Seek(0, 0);
        _bf.Serialize(_memoryStream, value);
        return _memoryStream.GetBuffer();
    }

    // Deserialize buffer to object
    public  object Deserialize(byte[] someBytes)
    {
        if (someBytes == null)
            return null;
        MemoryStream _memoryStream = new MemoryStream();
        _memoryStream.Write(someBytes, 0, someBytes.Length);
        _memoryStream.Seek(0, 0);
        var de = _bf.Deserialize(_memoryStream);
        return de;
    }

谢谢!

推荐答案

首先,您的序列化方法有一个错误:

First of all your serialize method has a bug:

即返回的数组大于序列化的数据

i.e. the array returns is larger than the serialized data

对于反序列化,您可以构造一个使用传入数组的内存流,因此它不会分配内部缓冲区.但是除非您有基准测试表明内存流分配确实是一个瓶颈,否则我不会打扰.

For deserializing you can construct a memory stream which uses the passed in array, so it won't allocate internal buffers. But unless you have benchmarks which show that memory stream allocation is really a bottleneck I wouldn't bother.

如果您确实要优化内存分配,则需要重用byte[]缓冲区.特别是这意味着修改api以与数组的子部分一起使用,因此消息大小和数组大小不必相同.

If you really want to optimize your memory allocations you'll need to reuse the byte[] buffers. This in particular means modifying the api to work with subsections of arrays so the message size and array size don't need to be identical.

以下是实现细节,可以随时更改(自从我读到它以来可能已经更改):
如果缓冲区没有出现在大对象堆上,那肯定不值得打扰.如果对象很小,它们将廉价地收集到下一个Gen0集合中.另一方面,大对象堆直接以Gen2结尾. > 250kB的AFAIR对象在那里分配.

The following are implementation details which can change at any time(and might already have changed since I read about it):
It's surely not worth bothering if the buffers don't end up on the large object heap. If the objects are small they'll be cheaply collected on the next Gen0 collection. The large object heap on the other hand directly ends up in Gen2. AFAIR objects >250kB are allocated there.

当然,重复使用缓冲区而没有缩小缓冲区可能会导致内存泄漏.

And of course reusing the buffers without ever shrinking them can be a memory leak.

这篇关于想要重用MemoryStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 04:47