当前位置:编程学习 > 网站相关 >>

数据序列化处理之经验积累(3) -- ObjectStateFormatter

这个序列化类,优势在于对基础类型存储在hashtable,pair,tripet等数据结构里的时候,序列化相对于binaryformatter和datacontractserializer有明显的优势。

    public static class ObjectStateFormatSerializer
    {
        private static readonly ObjectStateFormatter InnerStateFormatter = new ObjectStateFormatter();
        private readonly static MemoryStreamStack MemoryStreamStacker = new MemoryStreamStack();

        public static string SerializeToBase64String(object obj, bool compress)
        {
            byte[] bytes = Serialize(obj, compress);
            return Convert.ToBase64String(bytes);
        }

        public static T DeserializeFromBase64String<T>(string baseString, bool compress)
        {
            if (String.IsNullOrEmpty(baseString))
                return default(T);
            byte[] buf = Convert.FromBase64String(baseString);
            return Deserialize<T>(buf, compress);
        }

        public static byte[] Serialize(object obj, bool compress)
        {
            if (obj == null)
            {
                return null;
            }
            byte[] buf = null;
            MemoryStream stream = MemoryStreamStacker.GetMemoryStream();
            try
            {
                InnerStateFormatter.Serialize(stream, obj);
                stream.SetLength(stream.Position);
                buf = stream.ToArray();
                if (compress)
                {
                    buf = CompressHelper.CompressBytes(buf);
                }
            }
            finally
            {
                MemoryStreamStacker.ReleaseMemoryStream(stream);
            }
            return buf;
        }

        public static T Deserialize<T>(byte[] info, bool compress)
        {
            T ret = default(T);
            if (info == null || info.Length <= 0)
            {
                return ret;
            }
            if (compress)
            {
                info = CompressHelper.DeCompressBytes(info);
            }
            MemoryStream stream = MemoryStreamStacker.GetMemoryStream();
            try
            {
                stream.Write(info, 0, info.Length);
                stream.Position = 0L;
                ret = (T)InnerStateFormatter.Deserialize(stream);
            }
            finally
            {
                MemoryStreamStacker.ReleaseMemoryStream(stream);
            }
            return ret;
        }

    }

最后对我写的这3篇关于序列化的文章,做个小结,序列化和压缩要慎用,因为它们是吃cpu和内存的大户,除非非不得已或者业务量不是非常大的情况下可以使用,在高性能高吞吐量的系统中,与其直接用stirng的format来做对象的值的序列化后来传递和保存,也不要用它们,否则你就会看到你的服务器的cpu一直在 100%,而这个时候你并不知道你的服务器到底已经超负荷到什么程度了

 

补充:综合编程 , 其他综合 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,