Skip to content

Commit 7dddee9

Browse files
authored
Reduce allocations in C# when deserializing lists and arrays (#2688)
1 parent 0f70e63 commit 7dddee9

File tree

1 file changed

+24
-2
lines changed
  • crates/bindings-csharp/BSATN.Runtime/BSATN

1 file changed

+24
-2
lines changed

crates/bindings-csharp/BSATN.Runtime/BSATN/Runtime.cs

+24-2
Original file line numberDiff line numberDiff line change
@@ -403,8 +403,19 @@ public AlgebraicType GetAlgebraicType(ITypeRegistrar registrar) =>
403403
where ElementRW : IReadWrite<Element>, new()
404404
{
405405
private static readonly Enumerable<Element, ElementRW> enumerable = new();
406+
private static readonly ElementRW elementRW = new();
406407

407-
public Element[] Read(BinaryReader reader) => enumerable.Read(reader).ToArray();
408+
public Element[] Read(BinaryReader reader)
409+
{
410+
// Don't use Enumerable here: save an allocation and pre-allocate the output.
411+
var count = reader.ReadInt32();
412+
var result = new Element[count];
413+
for (var i = 0; i < count; i++)
414+
{
415+
result[i] = elementRW.Read(reader);
416+
}
417+
return result;
418+
}
408419

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

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

450-
public List<Element> Read(BinaryReader reader) => enumerable.Read(reader).ToList();
462+
public List<Element> Read(BinaryReader reader)
463+
{
464+
// Don't use Enumerable here: save an allocation and pre-allocate the output.
465+
var count = reader.ReadInt32();
466+
var result = new List<Element>(count);
467+
for (var i = 0; i < count; i++)
468+
{
469+
result.Add(elementRW.Read(reader));
470+
}
471+
return result;
472+
}
451473

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

0 commit comments

Comments
 (0)