Serialization taking too much time

孤街浪徒 提交于 2019-12-10 11:16:56

问题


Here is code which takes almost 3 to 8 sec for serialization depends on object type. I want to store this result into Redis for caching. But this operation is taking too long. Also same for deserialization.

public byte[] SerializeObject(object objectToSerialize)
{
    try
    {
        //If object to serialize is null then return null
        if (objectToSerialize == null)
            return null;

        byte[] result;
        //Create memory stream and use it for Serializing object
        using (var ms = new MemoryStream())
        {
            using (var zs = new GZipStream(ms, CompressionMode.Compress, true))
            {
                var bf = new BinaryFormatter();
                bf.Serialize(zs, objectToSerialize);
            }
            result = ms.ToArray();
        }
        return result;
    }
    catch (Exception ex)
    {
        //Some code
        return null;
    }
}

Updated: How I have tried serializing a DataTable:

using(var client = m_oRedisClientsManager.GetClient()) {
    //Serialize DataTable to byte
    byteCachedDatatable = m_oSerializer.SerializeDataTable(oCacheObject);

    //add Serialized bytes to redis and update expiration time
    client.Set(sCacheKey, byteCachedDatatable, new TimeSpan(0, iExpiryTimeInMins, 0));
}

public byte[] SerializeDataTable(DataTable dataTable) {
    if (dataTable == null) return null;
    byte[] result;
    using(var memoryStream = new MemoryStream()) {
        using(var deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress)) {
            dataTable.WriteXml(deflateStream, XmlWriteMode.WriteSchema);
            deflateStream.Flush();
            deflateStream.Close();
            result = memoryStream.ToArray();
        }
    }
    return result;
}

Any pointers will be helpful.

来源:https://stackoverflow.com/questions/20948459/serialization-taking-too-much-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!