简体   繁体   中英

Custom byte serializer

I have a dictionary of this type

Dictionary <byte, object> parameters = new Dictionary <byte, object> ();

As I write object data types int, long, float , etc.

I need to serialize this list into an array of bytes to be transmitted over the network. But here comes the problem: how do you know which type is in the object ? There iedya record into an array of bytes from one byte prefix which will contain the type of the variable. But you need to first know what type is in the object, once compare types, all this strongly loads a program. Maybe you have an idea how you can quickly and efficiently serialize this dictionary?

Now I have a code like this:

Class BinarySerializer

public static byte [] Serialize (short value) // get an array of bytes
{
    return BitConverter.GetBytes (value);
}

class where the serialization:

byte [] msg = new byte [256];

int offset = 0;
foreach (KeyValuePair <byte, object> pair in message.Parameters)
{
    msg [offset ++] = pair.Key;

    byte [] array = new byte [0];
    byte [] buffer;
    if (pair.Value.GetType (). Equals (typeof (short)))
    {
        msg [offset ++] = 1; // variable type
        buffer = BinarySerializer.Serialize ((short) pair.Value);
    }

    Buffer.BlockCopy (buffer, 0, msg, 0, buffer.Length);

    offset + = buffer.Length;
}

Its works, but slowly. Compare type of each variable is not good at all,

In that case, consider:

switch(Type.GetTypeCode(pair.Value.GetType()))
{
    case TypeCode.Int16: // aka short
       // ...
    // etc
}

But the more likely cause of performance issues here is allocations. Without a wider context of your code, and evidence of why you think it is slow: we can't comment much.

If you want blistering performance, though: don't use a dictionary . Consider:

var obj = new {
   Name = "Fred",
   Age = 18,
   IsActive = true
};

That is a fully typed class with named, typed values. You can use meta-programming (typically IL-emit or Expression ) to process such types very efficiently (as long as you cache the generated strategies). That is the approach that fully-developed serialization libraries like JSON.NET or protobuf-net use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM