我尝试了 Mono - 它在 1 毫秒内创建序列化程序,而 .NET 4.0 则为 60。可能有人将 Mono 序列化程序生成器移植为可重用的库?或者如果我尝试移植,可以给我要使用的 Mono 程序集的确切列表吗?
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace serialization
{
[Serializable]
public sealed class UserCredentials1
{
public string Username { get; set; }
public string Password { get; set; }
public override string ToString()
{
return string.Format("Username: {0}, Password: {1}", Username, Password);
}
}
[Serializable]
public sealed class UserCredentials2
{
public string Username { get; set; }
public string Password { get; set; }
public override string ToString()
{
return string.Format("Username: {0}, Password: {1}", Username, Password);
}
}
//.NET 4.0
//native=60.757
//compiled=2.2602
//Username: CTTTOM, Password: WoEIPX6Qqf11j9vKn01bAA==
//MONO:
//mono serialization.exe
//native=0.1589
//compiled=0.1337
//Username: CTTTOM, Password: WoEIPX6Qqf11j9vKn01bAA==
class Program
{
static void Main(string[] args)
{
string xml1 = @" " +
@" CTTTOM" +
@" WoEIPX6Qqf11j9vKn01bAA==" +
@"";
string xml2 = @"" +
@" CTTTOM" +
@" WoEIPX6Qqf11j9vKn01bAA==" +
@"";
//warm up
Type targetType1 = typeof(UserCredentials1);
XmlSerializer nativeSerializer1 = new XmlSerializer(targetType1);
Type targetType2 = typeof(UserCredentials2);
nativeSerializer1.Deserialize(new XmlTextReader(new StringReader(xml1)));
var native = new Stopwatch();
native.Start();
XmlSerializer nativeSerializer2 = new XmlSerializer(targetType2);
native.Stop();
Console.WriteLine("native=" + native.Elapsed.TotalMilliseconds);
var compiled = new Stopwatch();
compiled.Start();
var de = nativeSerializer2.Deserialize(new XmlTextReader(new StringReader(xml2)));
compiled.Stop();
Console.WriteLine("compiled=" + compiled.Elapsed.TotalMilliseconds);
Console.Write(de.ToString());
Console.ReadKey();
}
}
}
编辑
我迈出了迁移的第一步,请参阅https://github.com/asd-and-Rizzo/mono。使用“mono serialization.exe”对通用对象列表进行测试,单击鼠标运行 .NET 序列化和移植的 Mono 序列化。移植版本的默认序列化程序生成速度比 .NET 快约 10 倍。
编辑
在 MSDN 中找到关于 XML 序列化配置 .NET 4.5 (http://msdn.microsoft.com/en-us/library/ms229754.aspx):
useLegacySerializationGeneration 指定 XmlSerializer 是否使用遗留序列化生成,通过将 C# 代码写入文件然后将其编译为程序集来生成程序集。默认值为假。