0

I have a class that needs to be constantly serialized, because the info is read from a file outside of my app. My info classes can be represented by something like this:

[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; }
}

My problem is that every time I add a new element must write the full file, and this is creating unwanted performance. Something like this:

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

stream.SetLength(0);

serializer.Serialize(stream, log);

I've tried removing the cleaning process before writing but made ​​no difference to performance.performance. Does anyone have an idea to improve the performance?

EDITED

The number of elements in this collection exceeds 100,000.

Jonny Piazzi
  • 3,684
  • 4
  • 34
  • 81

2 Answers2

1

Streaming to a CSV or plain text file for logs would be a better solution than XML as you can simply append your log item to it.

If you must use XML, your are going to at least need to rewrite everything from your current position to the end of the file. Use a streamreader and streamwriter to copy the file up to the position you wish to insert, write your new data, then write the rest of the file. There will still be IO bottlenecks and the only thing you would gain with this approach is not serializing every object on each write.

Very similar to : In C#, is there a way to add an XML node to a file on disk WITHOUT loading it first?

Community
  • 1
  • 1
BinaryConstruct
  • 191
  • 1
  • 5
0

I think, you can improve performance using chaining an XmlReader/XmlWriter. Try looking this article http://msdn.microsoft.com/en-us/library/aa302289.aspx

oakio
  • 1,868
  • 1
  • 14
  • 21