Skip to content

Reduce allocations in C# when deserializing lists and arrays #2688

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 5, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions crates/bindings-csharp/BSATN.Runtime/BSATN/Runtime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -403,8 +403,19 @@ public AlgebraicType GetAlgebraicType(ITypeRegistrar registrar) =>
where ElementRW : IReadWrite<Element>, new()
{
private static readonly Enumerable<Element, ElementRW> enumerable = new();
private static readonly ElementRW elementRW = new();

public Element[] Read(BinaryReader reader) => enumerable.Read(reader).ToArray();
public Element[] Read(BinaryReader reader)
{
// Don't use Enumerable here: save an allocation and pre-allocate the output.
var count = reader.ReadInt32();
var result = new Element[count];
for (var i = 0; i < count; i++)
{
result[i] = elementRW.Read(reader);
}
return result;
}

public void Write(BinaryWriter writer, Element[] value) => enumerable.Write(writer, value);

Expand Down Expand Up @@ -446,8 +457,19 @@ public AlgebraicType GetAlgebraicType(ITypeRegistrar registrar) =>
where ElementRW : IReadWrite<Element>, new()
{
private static readonly Enumerable<Element, ElementRW> enumerable = new();
private static readonly ElementRW elementRW = new();

public List<Element> Read(BinaryReader reader) => enumerable.Read(reader).ToList();
public List<Element> Read(BinaryReader reader)
{
// Don't use Enumerable here: save an allocation and pre-allocate the output.
var count = reader.ReadInt32();
var result = new List<Element>(count);
for (var i = 0; i < count; i++)
{
result.Add(elementRW.Read(reader));
}
return result;
}

public void Write(BinaryWriter writer, List<Element> value) => enumerable.Write(writer, value);

Expand Down
Loading