我正在测试C#应用程序中的备用反序列化方法。我正在尝试ServiceStack(4.0.38),我发现了一些奇怪的行为。这是我的测试代码:
public class BasicObject
{
public List<string> Stuff { get; set; }
public BasicObject()
{
Stuff = new List<string>();
}
}
private void CustomTesting()
{
var largeObject = new BasicObject();
var mediumObject = new BasicObject();
var smallObject = new BasicObject();
//Populate this shiz
for (int i = 0; i < 100000; i++)
{
if (i < 50000)
mediumObject.Stuff.Add("HelloWorld");
if (i < 2000)
smallObject.Stuff.Add("HelloWorld");
largeObject.Stuff.Add("HelloWorld");
}
//Serialize, save to disk
using(var stream = new MemoryStream())
{
JsonSerializer.SerializeToStream<BasicObject>(largeObject, stream);
File.WriteAllBytes("C:\\Temp\\Large", stream.ToArray());
}
using (var stream = new MemoryStream())
{
JsonSerializer.SerializeToStream<BasicObject>(mediumObject, stream);
File.WriteAllBytes("C:\\Temp\\Medium", stream.ToArray());
}
using (var stream = new MemoryStream())
{
JsonSerializer.SerializeToStream<BasicObject>(smallObject, stream);
File.WriteAllBytes("C:\\Temp\\Small", stream.ToArray());
}
var watch = new Stopwatch();
using (var stream = new MemoryStream(File.ReadAllBytes("C:\\Temp\\Large")))
{
watch.Start();
var test = JsonSerializer.DeserializeFromStream<BasicObject>(stream);
watch.Stop();
}
var timeTakenLarge = watch.Elapsed.Milliseconds;
watch.Restart();
using (var stream = new MemoryStream(File.ReadAllBytes("C:\\Temp\\Medium")))
{
watch.Start();
var test = JsonSerializer.DeserializeFromStream<BasicObject>(stream);
watch.Stop();
}
var timeTakenMedium = watch.Elapsed.Milliseconds;
watch.Restart();
using (var stream = new MemoryStream(File.ReadAllBytes("C:\\Temp\\Small")))
{
watch.Start();
var test = JsonSerializer.DeserializeFromStream<BasicObject>(stream);
watch.Stop();
}
var timeTakenSmall = watch.Elapsed.Milliseconds;
watch.Restart();
Console.Clear();
Console.WriteLine(string.Format("{0} {1} {2}", timeTakenLarge, timeTakenMedium, timeTakenSmall));
Console.ReadKey();
}
非常简单,拿一个基本对象,用3个不同的数据范围填充它。序列化它,将其保存到磁盘。然后将获取的文件保存在内存流中,看看ServiceStack需要多长时间反序列化。这是我的输出(以毫秒为单位)
Deserialization Order: Large Med Small Display Order: Large Med Small 209 61 1 222 73 1 178 57 1 174 60 1 Deserialization Order: Small Med Large Display Order: Large Med Small 145 48 66 128 72 63 100 58 79 98 55 57 Deserialization Order: Med Small Large Display Order: Large Med Small 106 130 1 155 114 1 106 199 1 115 217 1
出于某种原因,首先发生反序列化会有点慢。为什么是这样? ServiceStack是否可以缓存有关幕后对象的信息?
答案 0 :(得分:1)
大多数序列化程序针对运行时性能进行了优化,其中第一次迭代将由于创建和编译包含最佳代码路径的所有必需委托而变慢,然后缓存并重新用于后续序列化缓存类型。 / p>