|
| 1 | +using System; |
| 2 | +using System.Buffers; |
| 3 | +using System.IO; |
| 4 | +using BenchmarkDotNet.Attributes; |
| 5 | +using Microsoft.AspNetCore.Http.Connections.Client.Internal; |
| 6 | +using Microsoft.AspNetCore.Http.Connections.Internal; |
| 7 | +using Microsoft.AspNetCore.SignalR.Internal.Protocol; |
| 8 | + |
| 9 | +namespace Microsoft.AspNetCore.SignalR.Microbenchmarks |
| 10 | +{ |
| 11 | + public class ServerSentEventsBenchmark |
| 12 | + { |
| 13 | + private ServerSentEventsMessageParser _parser; |
| 14 | + private byte[] _sseFormattedData; |
| 15 | + private byte[] _rawData; |
| 16 | + |
| 17 | + [Params(Message.NoArguments, Message.FewArguments, Message.ManyArguments, Message.LargeArguments)] |
| 18 | + public Message Input { get; set; } |
| 19 | + |
| 20 | + [GlobalSetup] |
| 21 | + public void GlobalSetup() |
| 22 | + { |
| 23 | + var hubProtocol = new JsonHubProtocol(); |
| 24 | + HubMessage hubMessage = null; |
| 25 | + switch (Input) |
| 26 | + { |
| 27 | + case Message.NoArguments: |
| 28 | + hubMessage = new InvocationMessage(target: "Target", argumentBindingException: null); |
| 29 | + break; |
| 30 | + case Message.FewArguments: |
| 31 | + hubMessage = new InvocationMessage(target: "Target", argumentBindingException: null, 1, "Foo", 2.0f); |
| 32 | + break; |
| 33 | + case Message.ManyArguments: |
| 34 | + hubMessage = new InvocationMessage(target: "Target", argumentBindingException: null, 1, "string", 2.0f, true, (byte)9, new int[] { 5, 4, 3, 2, 1 }, 'c', 123456789101112L); |
| 35 | + break; |
| 36 | + case Message.LargeArguments: |
| 37 | + hubMessage = new InvocationMessage(target: "Target", argumentBindingException: null, new string('F', 10240), new string('B', 10240)); |
| 38 | + break; |
| 39 | + } |
| 40 | + |
| 41 | + _parser = new ServerSentEventsMessageParser(); |
| 42 | + _rawData = hubProtocol.WriteToArray(hubMessage); |
| 43 | + var ms = new MemoryStream(); |
| 44 | + ServerSentEventsMessageFormatter.WriteMessage(_rawData, ms); |
| 45 | + _sseFormattedData = ms.ToArray(); |
| 46 | + } |
| 47 | + |
| 48 | + [Benchmark] |
| 49 | + public void ReadSingleMessage() |
| 50 | + { |
| 51 | + var buffer = new ReadOnlySequence<byte>(_sseFormattedData); |
| 52 | + |
| 53 | + if (_parser.ParseMessage(buffer, out _, out _, out _) != ServerSentEventsMessageParser.ParseResult.Completed) |
| 54 | + { |
| 55 | + throw new InvalidOperationException("Parse failed!"); |
| 56 | + } |
| 57 | + |
| 58 | + _parser.Reset(); |
| 59 | + } |
| 60 | + |
| 61 | + [Benchmark] |
| 62 | + public void WriteSingleMessage() |
| 63 | + { |
| 64 | + ServerSentEventsMessageFormatter.WriteMessage(_rawData, Stream.Null); |
| 65 | + } |
| 66 | + |
| 67 | + public enum Message |
| 68 | + { |
| 69 | + NoArguments = 0, |
| 70 | + FewArguments = 1, |
| 71 | + ManyArguments = 2, |
| 72 | + LargeArguments = 3 |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments