Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get sub array without cloning

Tags:

c#

I know in C# we can always get the sub-array of a given array by using Array.Copy() method. However, this will consume more memory and processing time which is unnecessary in read-only situation. For example, I'm writing a heavy load network program which exchanges messages with other nodes in the cluster very frequently. The first 20 bytes of every message is the message header while the rest bytes make up the message body. Therefore, I will divide the received raw message into header byte array and body byte array in order to process them separately. However, this will obviously consume double memory and extra time. In C, we can easily use a pointer and assign offset to it to access different parts of the array. For instance, in C language, if we have a char a[] = "ABCDEFGHIJKLMN", we can declare a char* ptr = a + 3 to represent the array DEFGHIJKLMN.

Is there a way to accomplish this in C#?

like image 650
House.Lee Avatar asked Jul 17 '15 03:07

House.Lee


2 Answers

You might be interested in ArraySegments or unsafe.


ArraySegments delimits a section of a one-dimensional array.

Check ArraySegments in action

ArraySegments usage example:

 int[] array = { 10, 20, 30 };

 ArraySegment<int> segment = new ArraySegment<int>(array, 1, 2);
 // The segment contains offset = 1, count = 2 and range = { 20, 30 }

Unsafe define an unsafe context in which pointers can be used.

Unsafe usage example:

    int[] a = { 4, 5, 6, 7, 8 };

    unsafe
    {
        fixed (int* c = a)
        {
            // use the pointer
        }
    }
like image 157
gastonmancini Avatar answered Sep 21 '22 15:09

gastonmancini


First of all you must consider this as a premature optimization.

But you may use several ways to reduce memory consumption, if you sure you really need it:

1) You may use Flyweight pattern https://en.wikipedia.org/wiki/Flyweight_pattern to pool duplicated resources.

2) You may try to use unsafe directive and manual pointer management.

3) You may just switch to C for this functionality and just call native code from your C# program.

From my experience memory consumption for short-lived objects is not a big problem and I'd just write code with flyweight pattern and profile application afterwards.

like image 29
Mikhail Aksenov Avatar answered Sep 25 '22 15:09

Mikhail Aksenov