C#/.NET:用于网络的 UnmanagedMemoryStream?

发布于 2024-09-28 10:51:56 字数 559 浏览 6 评论 0 原文

我正在考虑使用 UnmanagementMemoryStream 而不是 MemoryStream 来处理网络服务器中的传入(也许还有传出?)数据包。我希望实现的是减少值的复制,并且如果可能的话,避免复制到堆(太多)。

例如,对于传入的数据包,可以这样做:

fixed (byte* p = &data) // where data comes from a socket receive
{
    using (var stream = new UnmanagedMemoryStream(p, data.Length))
    {
        // do handling here...
    }
}

尽管如此,我不太确定这样做是否有任何实际好处。任何人都可以提供一些反馈来说明这样做是否有任何价值,而不是使用良好的旧托管 MemoryStream?

提前致谢。

I was considering using UnmanagedMemoryStream rather than MemoryStream for dealing with incoming (and perhaps outgoing?) packets in a network server. What I hope to achieve is less copying of values, and if possible, avoid copying to the heap (too much).

For example, for an incoming packet, one could do:

fixed (byte* p = &data) // where data comes from a socket receive
{
    using (var stream = new UnmanagedMemoryStream(p, data.Length))
    {
        // do handling here...
    }
}

Still, I'm not quite sure if there is any realistic benefit in doing this. Could anyone come with some feedback as to whether or not there would be any value in doing this, rather than using the good old managed MemoryStream?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

与风相奔跑 2024-10-05 10:51:56

对我来说,这听起来像是过早的优化。您是否使用过 MemoryStream 并进行了一些分析以表明它给您带来了切实的、可测量的性能问题?

我会坚持使用传统的 MemoryStream,这样可以避免让自己头疼,直到(通过分析)发现有必要进行更改为止。

This sounds like premature optimization to me. Have you used MemoryStream and done some profiling to show that it caused you tangible, measurable performance problems?

I would stick with the conventional MemoryStream and save myself the headache until it became obvious (through profiling) that it was necessary to change.

月棠 2024-10-05 10:51:56

不,你没有改进已有的东西。 byte[] 是引用类型。您可以简单地将其传递给 MemoryStream(byte[]) 构造函数,并且不会复制任何数据。 MS 只是存储对同一数组的引用。

事实上,你让情况变得更糟,因为你固定了阵列。让垃圾收集在代码片段体内运行并不是不可能的,您正在从数组中读取内容,并且可能正在从数据、字符串等创建对象。垃圾收集器需要围绕固定数组工作,这使其工作变得更加困难。这实际上会在一段时间内影响程序的性能,压缩堆对于提高 CPU 缓存的效率非常重要。

Nope, you didn't improve what is already there. A byte[] is a reference type. You can simply pass it to the MemoryStream(byte[]) constructor and no data is getting copied. MS simply stores a reference to the same array.

In fact, you made it worse because you pinned the array. Getting a garbage collection to run inside the body of your snippet isn't unlikely, you are reading stuff from the array and are probably creating objects from the data, strings and what-not. The garbage collector needs to work around the pinned array, making its life considerably more difficult. This can actually affect the perf of your program for a while, compacting the heap is important to make the CPU cache efficient.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文