Steven S.
Steven S.

Reputation: 734

BinaryFormatter becomes slower than XmlSerializer the more Items I Serialize/Deserialize

I have following Extension Methods to clone a list with items:

    public static class MyExtensionMethods
    {
        public static T CloneXml<T>(this T source)
        {
            var stream = new MemoryStream();
            var xmls = new XmlSerializer(typeof(T));
            xmls.Serialize(stream, source);
            stream.Seek(0, SeekOrigin.Begin);
            return (T)xmls.Deserialize(stream);
        }

        public static T CloneBinary<T>(this T source)
        {
            var formatter = new BinaryFormatter();
            var stream = new MemoryStream();
            formatter.Serialize(stream, source);
            stream.Seek(0, SeekOrigin.Begin);
            return (T)formatter.Deserialize(stream);
        }
    }

For the test I use the following object:

[Serializable]
public class MyItem
{
    public string Name { get; set; }
}

Now when I clone a list of 100 MyItem objects, the BinaryFormatter solution (1ms) will be a lot faster than my XmlSerializer solution (110ms). But if I have 100000 MyItem objects in the list, the BinaryFormatter solution (1s) will be slower than the XmlSerializer solution (450ms).

What's going on here?

Upvotes: 0

Views: 1561

Answers (2)

sandos
sandos

Reputation: 852

That is likely because of a performance issue with binaryformatter that is fixed in later .net versions:

When BinaryFormatter encounters a larger object list it gets quadratic deserialization times due to the linear search in

https://github.com/dotnet/corefx/issues/16991

And the fix:

This fix is scheduled to be included in .NET Framework 4.7.2 update. It won't be enabled by default. It will be only enabled when Switch.System.Runtime.Serialization.UseNewMaxArraySize config switch is set.

Upvotes: 2

user1519979
user1519979

Reputation: 1874

Binary formatte searlizes all metadata like type, assembly information.

The XMLSerializer just serializes to a schema (public fields, values of object). so i think that's the reason why it's faster

http://blogs.msdn.com/b/youssefm/archive/2009/07/10/comparing-the-performance-of-net-serializers.aspx

Upvotes: 1

Related Questions