-
-
Save layomia/2ff8c065f0f4933c4b22f7a277b03457 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
using System.Linq; | |
using System.Text.Json; | |
using System.Text.Json.Serialization; | |
using BenchmarkDotNet.Attributes; | |
namespace MiscBenchmarks | |
{ | |
[MemoryDiagnoser] | |
public class SerializerMethods_Array | |
{ | |
private MemoryStream _memoryStream; | |
private Utf8JsonWriter _jsonWriter; | |
private Person[] _data; | |
[Params(10, 100, 1000)] | |
public int Count; | |
[GlobalSetup] | |
public void Setup() | |
{ | |
_memoryStream = new MemoryStream(); | |
_jsonWriter = new Utf8JsonWriter(_memoryStream); | |
_data = DataGenerator.GetPeople(Count); | |
} | |
[GlobalCleanup] | |
public void Cleanup() | |
{ | |
_memoryStream.Dispose(); | |
_jsonWriter.Dispose(); | |
} | |
[Benchmark(Baseline = true)] | |
public void Serializer() | |
{ | |
JsonSerializer.Serialize(_jsonWriter, _data); | |
_memoryStream.SetLength(0);; | |
_jsonWriter.Reset(); | |
} | |
[Benchmark] | |
public void SrcGenSerializer() | |
{ | |
JsonSerializer.Serialize(_jsonWriter, _data, MyJsonContext.Default.PersonArray); | |
_memoryStream.SetLength(0);; | |
_jsonWriter.Reset(); | |
} | |
} | |
[JsonSerializable(typeof(Person[]))] | |
internal partial class MyJsonContext : JsonSerializerContext { } | |
internal static class DataGenerator | |
{ | |
private static readonly string[] FirstNames = new[] | |
{ | |
"Steffan", "Garin", "Fahad", "Eliana", "Thea", "Edmund", "Layla", "Tony", "Zakir", "Ariyah" | |
}; | |
private static readonly string[] LastNames = new[] | |
{ | |
"English", "Holder", "Beech", "Simon", "Briggs", "Terry", "Horton", "Leblanc", "Rodriguez", "Atkins" | |
}; | |
public static Person GetPerson() => GetPeople(1)[0]; | |
public static Person[] GetPeople(int num) | |
{ | |
Random rng = new(); | |
return Enumerable.Range(1, num).Select(indexer => new Person() | |
{ | |
FirstName = FirstNames[rng.Next(FirstNames.Length)], | |
LastName = LastNames[rng.Next(LastNames.Length)] | |
}).ToArray(); | |
} | |
} | |
internal sealed class Person | |
{ | |
public string FirstName { get; set; } | |
public string LastName { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment