C#/.NET:用于网络的 UnmanagedMemoryStream?
我正在考虑使用 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?
提前致谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对我来说,这听起来像是过早的优化。您是否使用过 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.
不,你没有改进已有的东西。 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.