views:

93

answers:

2

Hi!

People tend to recommend to cache XmlSerializer instances. Is this still actual? (if no, when has it become so?).

Also I came up with the following code and ask to review it.

  • Does it have any drawbacks?
  • Will it use many threads\cores for different types?
  • How can I improve it?

The code:

public static class SerializerFactory<T>
{
    public static readonly XmlSerializer Serializer = new XmlSerializer(typeof(T));
}

and usage:

var obj = (T)XmlSerializerFactory<T>.Serializer.Deserialize(input);
+2  A: 

When you use the XmlSerializer(Type) or XmlSerializer(Type,String) constructors then the serialization assembly will be cached so there is very little overhead in creating a new serializer instance (source).

So as your factory would use this constructor, there's no real point to it. You may as well just use the constructor directly.

Greg Beech
A: 

I would recommend this instead:

public static class SerializerFactory<T>
{
    static readonly XmlSerializer serializer = new XmlSerializer(typeof(T));

    public static XmlSerializer 
    { 
        get { return serializer; }
    }
}

Even when you have static readonly fields it is best to use properties to access them.

Andrew Hare
Any particular reason why? My opinion: more code --> worse code.
Konstantin Spirin