【问题标题】:Reuse Previous Serialization in File with System.Xml.Serialization使用 System.Xml.Serialization 在文件中重用以前的序列化
【发布时间】:2013-07-16 19:21:59
【问题描述】:

我有一个需要不断序列化的类,因为信息是从我的应用程序外部的文件中读取的。我的信息类可以这样表示:

[XmlRoot("log")]
public class Log
{
    [XmlArray("infos")]
    [XmlArrayItem("info")]
    public List<Item> Infos { get; set; }
}

public class Item
{
    [XmlElement("time")]
    public DateTime Time { get; set; }

    [XmlElement("info")]
    public string Info { get; set; }
}

我的问题是每次添加新元素时都必须写入完整文件,这会造成不必要的性能。像这样的:

var serializer = new XmlSerializer(typeof(Log));

stream.SetLength(0);

serializer.Serialize(stream, log);

我在写之前试过去掉清理过程但是对performance.performance没有影响。有没有人有提高性能的想法?

已编辑

此集合中的元素数量超过 100,000。

【问题讨论】:

    标签: c# .net xml serialization file-io


    【解决方案1】:

    将日志流式传输到 CSV 或纯文本文件将是比 XML 更好的解决方案,因为您可以简单地将日志项附加到它。

    如果您必须使用 XML,您至少需要重写从当前位置到文件末尾的所有内容。使用流读取器和流写入器将文件复制到您希望插入的位置,写入新数据,然后写入文件的其余部分。仍然会存在 IO 瓶颈,使用这种方法唯一可以获得的好处是不会在每次写入时序列化每个对象。

    非常类似于:In C#, is there a way to add an XML node to a file on disk WITHOUT loading it first?

    【讨论】:

      【解决方案2】:

      我认为,您可以使用链接 XmlReader/XmlWriter 来提高性能。 试试看这篇文章http://msdn.microsoft.com/en-us/library/aa302289.aspx

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-05
        • 1970-01-01
        • 2013-04-26
        • 1970-01-01
        • 2021-04-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多