Skip to content

MessagePack for C# v4: Round7 - #2294

Draft
neuecc wants to merge 8 commits into
masterfrom
v4
Draft

MessagePack for C# v4: Round7#2294
neuecc wants to merge 8 commits into
masterfrom
v4

Conversation

@neuecc

@neuecc neuecc commented Aug 28, 2026

Copy link
Copy Markdown
Member

In this round, we finished building out the Source Generator and implemented all remaining features.
While the code polishing and final review are not complete yet, we consider the implementation of all planned features to be done.

First of all: v4 achieves extremely fast serialization/deserialization speed even in map mode!
It is even faster than other libraries' array mode.

Serialize

Method Mean Ratio
v4 array 411.0 ns 1.00
v4 map 543.8 ns 1.32
v3 array 1,367.9 ns 3.33
v3 map 1,610.2 ns 3.92
Nerdbank array 1,035.7 ns 2.52
Nerdbank map 1,757.4 ns 4.28
Orleans 1,422.6 ns 3.46
protobuf-net 1,742.2 ns 4.24
System.Text.Json 3,176.6 ns 7.73
Newtonsoft.Json 6,405.2 ns 15.58

Deserialize

Method Mean Ratio
v4 array 895.4 ns 1.00
v4 map 1,197.8 ns 1.34
v3 array 2,075.1 ns 2.32
v3 map 3,111.8 ns 3.48
Nerdbank array 1,829.7 ns 2.04
Nerdbank map 3,532.0 ns 3.94
Orleans 1,806.0 ns 2.02
protobuf-net 2,079.4 ns 2.32
System.Text.Json 5,623.1 ns 6.28
Newtonsoft.Json 11,073.6 ns 12.37

You may notice that v3's performance looks quite bad here. For the sake of benchmark fairness, we use Jil's Stackoverflow Answer as the large POCO, and all of its primitive fields are nullable. v3's Source Generator handles nullables poorly, which causes this performance degradation. Since this is not a particularly common scenario, we may switch to a benchmark with the nullables removed.

As for Nerdbank.MessagePack, it has been updated to the latest v1.3.85, which is why its array performance has improved significantly.

New Features

We added support for the new .NET 11 types and C# 15 unions.

[MessagePackObject]
[UnionTag<Cat>(0)]
[UnionTag<Dog>(1)]
[UnionTag<Bird>(2)]
public union Pet(Cat, Dog, Bird);

We also support the non-boxing access pattern, so when the case types are structs, this finally delivers the long-requested unions over value types.

Note that as a breaking change to the annotations, MessagePack.UnionAttribute is renamed to MessagePack.UnionTag. The reason is that it collides with System.Runtime.CompilerServices.UnionAttribute, which makes it awkward to use.

We intend to take the utmost care with annotation compatibility, but there is one more break: the Type of MessagePackFormatterAttribute is now a factoryType instead of a formatterType, which is not compatible. Due to the architectural change, formatters can no longer be instantiated directly, so this change is unavoidable.

In addition, the generator-related attributes (MessagePackAssumedFormattableAttribute, MessagePackKnownFormatterAttribute) are retired. In their place, MessagePackSerializableAttribute and MessagePackKnownTypeAttribute are introduced.

// The Source Generator implements MessagePackFormatterFactory and registers it to SourceGeneratedFormatterFactory automatically
[MessagePackSerializable<SandboxPerson[]>]
public partial class RootFactory;

By passing a KeyNamingPolicy at declaration time, you can now apply name conversion in the automatic map mode.

[MessagePackObject(KeyNamingPolicy.SnakeCaseLower)]
public class SandboxPerson
{
    public required int Id { get; init; } // id
    public string? Name { get; set; } // name
    public string[]? MyTags { get; set; } // my_tags
}

We also added the options ValidateRequiredMembers and ValidateNullableAnnotations, which validate required and nullable respectively. The defaults are true for required and false for nullable. Because of the nature of the language, nullable validation can never be 100% complete, so we judged that opting in deliberately, with an understanding of its limitations, is the better default.

Circular references and dedup are now supported. Wrapping every formatter has real problems (versioning resilience, efficiency, and the implementation bleeding into every formatter), so we chose a per-type opt-in approach for the types you want to support. I believe this is a well-balanced approach that poses no problems in practice.

[MessagePackObject(AllowCircularReferences = true)]
public class Node
{
    [Key(0)]
    public Node? Parent { get; set; }
    [Key(1)]
    public List<Node> Children { get; set; } = [];
    [Key(2)]
    public string? Name { get; set; }
}

As the equivalent of protobuf's Unknown Fields, we introduce MessagePackUnknownMembers.

[MessagePackObject]
public struct Foo
{
    [Key(0)]
    public int Id { get; set; }
    [Key(1)]
    public string? Name { get; set; }

    public MessagePackUnknownMembers? Extra { get; set; }
}

We added IMessagePackSurrogate<TTarget, TSurrogate>, which makes external types without annotations serializable without writing a custom formatter. Once defined, the Source Generator automatically adds it to the standard runtime factory as well, so it automatically becomes serializable in AOT environments too. Note that since it uses static abstract members, it targets modern .NET only.

[MessagePackObject]
public struct UserIdSurrogate : IMessagePackSurrogate<UserId, UserIdSurrogate>
{
    [Key(0)]
    public int Value { get; }

    [Key(1)]
    public string Realm { get; }

    public UserIdSurrogate(int value, string realm)
    {
        this.Value = value;
        this.Realm = realm;
    }

    public static UserIdSurrogate ToSurrogate(UserId value)
    {
        return new UserIdSurrogate(value.Value, value.Realm);
    }

    public static UserId FromSurrogate(UserIdSurrogate surrogate)
    {
        return new UserId(surrogate.Value, surrogate.Realm);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant