對如下數據類生成用于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。