-
-
Save layomia/77b91c8ea446b50efbcf358a19d73be1 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; | |
using System.Diagnostics; | |
using System.Text.Json; | |
using System.IO; | |
using System.Buffers; | |
#if SERIALIZER_NEW | |
using System.Text.Json.Serialization; | |
using System.Text.Json.Serialization.Metadata; | |
using Startup; | |
#endif | |
namespace Startup | |
{ | |
class Program | |
{ | |
private static byte[] s_serialized = new byte[] { 123, 34, 109, 101, 115, 115, 97, 103, 101, 34, 58, 34, 72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33, 34, 125 }; | |
private static JsonMessage message = new JsonMessage { message = "Hello, World!" }; | |
#if SERIALIZER_OLD | |
private static JsonSerializerOptions s_oldPatternOptions = new(); | |
#elif SERIALIZER_NEW | |
private static JsonTypeInfo<JsonMessage> s_newPatternMetadata = JsonContext.Default.JsonMessage; | |
#endif | |
static void Main(string[] args) | |
{ | |
Stopwatch sw = new(); | |
Process process = Process.GetCurrentProcess(); | |
process.Refresh(); | |
long oldPrivateBytes = process.PrivateMemorySize64 / 1024; | |
sw.Start(); | |
#if SERIALIZE | |
RunSerializeBenchMark(); | |
#else | |
RunDeserializeBenchMark(); | |
#endif | |
sw.Stop(); | |
process.Refresh(); | |
long newPrivateBytes = process.PrivateMemorySize64 / 1024; | |
Console.Write("Private bytes (KB): "); | |
Console.WriteLine(newPrivateBytes - oldPrivateBytes); | |
Console.Write("Elapsed time (ms):"); | |
Console.WriteLine(sw.ElapsedMilliseconds); | |
} | |
private static void RunSerializeBenchMark() | |
{ | |
using MemoryStream ms = new(); | |
using Utf8JsonWriter writer = new(ms); | |
#if SERIALIZER_OLD | |
JsonSerializer.Serialize(writer, message, s_oldPatternOptions); | |
#elif SERIALIZER_NEW | |
JsonSerializer.Serialize(writer, message, s_newPatternMetadata); | |
#endif | |
} | |
private static void RunDeserializeBenchMark() | |
{ | |
#if SERIALIZER_OLD | |
_ = JsonSerializer.Deserialize<JsonMessage>(s_serialized, s_oldPatternOptions); | |
#elif SERIALIZER_NEW | |
_ = JsonSerializer.Deserialize(s_serialized, s_newPatternMetadata); | |
#endif | |
} | |
} | |
public class JsonMessage | |
{ | |
public string message { get; set; } | |
} | |
#if SERIALIZER_NEW | |
[JsonSerializable(typeof(JsonMessage))] | |
internal partial class JsonContext : JsonSerializerContext { } | |
#endif | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment