|
| 1 | +using BenchmarkDotNet.Attributes; |
| 2 | +using ModelContextProtocol; |
| 3 | +using ModelContextProtocol.Protocol; |
| 4 | +using System.Text.Json; |
| 5 | +using System.Text.Json.Nodes; |
| 6 | + |
| 7 | +public class JsonRpcMessageDeserializationBenchmarks |
| 8 | +{ |
| 9 | + private byte[] _requestJson = null!; |
| 10 | + private byte[] _notificationJson = null!; |
| 11 | + private byte[] _responseJson = null!; |
| 12 | + private byte[] _errorJson = null!; |
| 13 | + private JsonSerializerOptions _options = null!; |
| 14 | + |
| 15 | + [GlobalSetup] |
| 16 | + public void Setup() |
| 17 | + { |
| 18 | + _options = McpJsonUtilities.DefaultOptions; |
| 19 | + |
| 20 | + _requestJson = JsonSerializer.SerializeToUtf8Bytes( |
| 21 | + new JsonRpcRequest |
| 22 | + { |
| 23 | + Id = new RequestId("1"), |
| 24 | + Method = "test", |
| 25 | + Params = JsonValue.Create(1) |
| 26 | + }, |
| 27 | + _options); |
| 28 | + |
| 29 | + _notificationJson = JsonSerializer.SerializeToUtf8Bytes( |
| 30 | + new JsonRpcNotification |
| 31 | + { |
| 32 | + Method = "notify", |
| 33 | + Params = JsonValue.Create(2) |
| 34 | + }, |
| 35 | + _options); |
| 36 | + |
| 37 | + _responseJson = JsonSerializer.SerializeToUtf8Bytes( |
| 38 | + new JsonRpcResponse |
| 39 | + { |
| 40 | + Id = new RequestId("1"), |
| 41 | + Result = JsonValue.Create(3) |
| 42 | + }, |
| 43 | + _options); |
| 44 | + |
| 45 | + _errorJson = JsonSerializer.SerializeToUtf8Bytes( |
| 46 | + new JsonRpcError |
| 47 | + { |
| 48 | + Id = new RequestId("1"), |
| 49 | + Error = new JsonRpcErrorDetail { Code = 42, Message = "oops" } |
| 50 | + }, |
| 51 | + _options); |
| 52 | + } |
| 53 | + |
| 54 | + [Benchmark] |
| 55 | + public JsonRpcMessage DeserializeRequest() => |
| 56 | + JsonSerializer.Deserialize<JsonRpcMessage>(_requestJson, _options)!; |
| 57 | + |
| 58 | + [Benchmark] |
| 59 | + public JsonRpcMessage DeserializeNotification() => |
| 60 | + JsonSerializer.Deserialize<JsonRpcMessage>(_notificationJson, _options)!; |
| 61 | + |
| 62 | + [Benchmark] |
| 63 | + public JsonRpcMessage DeserializeResponse() => |
| 64 | + JsonSerializer.Deserialize<JsonRpcMessage>(_responseJson, _options)!; |
| 65 | + |
| 66 | + [Benchmark] |
| 67 | + public JsonRpcMessage DeserializeError() => |
| 68 | + JsonSerializer.Deserialize<JsonRpcMessage>(_errorJson, _options)!; |
| 69 | +} |
0 commit comments