Skip to content

Commit

Permalink
Avoid double emeration for SingleOrMany serialization (#6538)
Browse files Browse the repository at this point in the history
  • Loading branch information
stevejgordon authored Jul 14, 2022
1 parent 9214966 commit 6c13d40
Showing 1 changed file with 15 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,21 @@ public static IEnumerable<TItem> Deserialize<TItem>(ref Utf8JsonReader reader, J

public static void Serialize<TItem>(IEnumerable<TItem> value, Utf8JsonWriter writer, JsonSerializerOptions options)
{
// TODO - Optimise to avoid the count
var count = value.Count();
if (value is not ICollection<TItem> collection)
{
// Avoid a double enumeration of counting then iterating.
// Instead, produce an array, even if it's an array of one.

writer.WriteStartArray();
foreach (var item in value)
{
JsonSerializer.Serialize<TItem>(writer, item, options);
}
writer.WriteEndArray();
return;
}

var count = collection.Count;

if (count == 0)
{
Expand Down

0 comments on commit 6c13d40

Please sign in to comment.