数据序列化处理之经验积累(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%,而这个时候你并不知道你的服务器到底已经超负荷到什么程度了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值