测试string.Format、$、MessagePack、ZeroFormatter、DataContractJsonSerializer、Newtonsoft.Json的速度

对如下数据类生成用于Dictionary存储的Key值:

[DataContract]
[ZeroFormattable]
[MessagePackObject]
public class STPInvestorPositionField
{
    ///投资者代码
    [Index(0)]
    [Key(0)]
    [DataMember]
    public virtual string InvestorID { get; set; }
    ///交易所代码
    [Index(1)]
    [Key(1)]
    [DataMember]
    public virtual string ExchangeID { get; set; }
    ///策略代码
    [Index(2)]
    [Key(2)]
    [DataMember]
    public virtual string ComboID { get; set; }
    ///合约代码
    [Index(3)]
    [Key(3)]
    [DataMember]
    public virtual string InstrumentID { get; set; }
};

测试说明

测试机器:


测试台式机配置简要信息
  • 使用Windows 7的QueryPerformanceCounter作为计时工具。

  • Visual Studio 2017

  • 使用的是.Net Framework 4.6.1。

  • times=3000000

  • 所有序列化方式最终都生成string类型数据。

  • 仅使用第一个CPU内核。

     private static void SetThreadAffinity()
      {
          Process Proc = Process.GetCurrentProcess();
          long AffinityMask = (long)Proc.ProcessorAffinity;
          AffinityMask &= 0x0001; // use only the first processor
          Proc.ProcessorAffinity = (IntPtr)AffinityMask;
      }
    

测试结果

[Debug mode]
$string (tenths of ms) 5642
string.Format (tenths of ms) 5959
ZeroFormatterSerializer.Serialize (tenths of ms) 21483, Convert.ToBase64String() used.
MessagePackSerializer.Serialize (tenths of ms) 8077
MessagePackSerializer.Serialize (tenths of ms) 11223, Convert.ToBase64String() used.
MessagePackSerializer.Serialize (tenths of ms) 12362, Encoding.Default.GetString() used.
DataContractJsonSerializer (tenths of ms) 47525
Newtonsoft.Json (tenths of ms) 37426

[Release mode]
$string (tenths of ms) 5695
string.Format (tenths of ms) 6953
ZeroFormatterSerializer.Serialize (tenths of ms) 13883, Convert.ToBase64String() used.
MessagePackSerializer.Serialize (tenths of ms) 7648
MessagePackSerializer.Serialize (tenths of ms) 10530, Convert.ToBase64String() used.
MessagePackSerializer.Serialize (tenths of ms) 11800, Encoding.Default.GetString() used.
DataContractJsonSerializer (tenths of ms) 47304
Newtonsoft.Json (tenths of ms) 35031

测试结果说明:

  • 最快的还是$string方式。虽然说“$”是string.Format()的快捷方式,但是内部实现稍有不同。
  • 如果要使用Attribute方式实现自动化key生成,最快的方式是使用MessagePackSerializer。
  • Convert.ToBase64String的速度比System.Text.Encoding.Default.GetString更快一些。
  • 如果不使用Convert.ToBase64String,MessagePackSerializer.Serialize的速度接近于string.Format。因为为了便于Key值直接比较(byte[]不能使用“==”),还是要转换成string类型。
  • 综上,决定使用MessagePackSerializer.Serialize。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容