ArraySegment - Returning the actual segment C#

前端 未结 4 533
野性不改
野性不改 2020-12-10 02:50

I have been looking around on ways to return the segment which is basically held by ArraySegment in terms of offset and count. Although ArraySegment holds the complete and o

4条回答
  •  有刺的猬
    2020-12-10 03:33

    C# (and .NET in general) doesn't allow you to create a standard array reference that 'points to' the inside of another array. As such, you either need to change your consuming APIs so that they can deal with ArraySegment instances or you need to create a copy of the data and then copy the changes back after operating on the copy. This is generally a safer approach anyway, as passing around references to an array breaks insulation and makes it more difficult to track down bugs as the number of consumers of the array increases. Constructing new array instances and copying values is relatively cheap in .NET, as long as the arrays are not extremely large in size, so the performance impact here is generally negligible.

    If you're running into performance problems and you need to micro-optimize, I would recommend using either unsafe C# code (where you can fix the array reference and pass around pointers) or pulling out the performance-critical code to a C++/CLI assembly where you can do the computations with unmanaged memory. I would recommend profiling the code first to verify that this is really your bottleneck. I can't stress enough that you shouldn't fear allocating new memory in .NET, as the nature of the compacting GC heap means that frequent small allocations are cheaper than they would be in C (where memory allocation must accommodate for possible heap fragmentation.)

提交回复
热议问题