You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SerializerBenchmark.cs 2.1 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using BenchmarkDotNet.Attributes;
  2. using MQTTnet.Packets;
  3. using MQTTnet.Serializer;
  4. using MQTTnet.Internal;
  5. using BenchmarkDotNet.Attributes.Jobs;
  6. using BenchmarkDotNet.Attributes.Exporters;
  7. using System;
  8. using System.Threading;
  9. using System.IO;
  10. using MQTTnet.Core.Internal;
  11. namespace MQTTnet.Benchmarks
  12. {
  13. [ClrJob]
  14. [RPlotExporter]
  15. [MemoryDiagnoser]
  16. public class SerializerBenchmark
  17. {
  18. private MqttBasePacket _packet;
  19. private ArraySegment<byte> _serializedPacket;
  20. private MqttPacketSerializer _serializer;
  21. [GlobalSetup]
  22. public void Setup()
  23. {
  24. var message = new MqttApplicationMessageBuilder()
  25. .WithTopic("A")
  26. .Build();
  27. _packet = message.ToPublishPacket();
  28. _serializer = new MqttPacketSerializer();
  29. _serializedPacket = _serializer.Serialize(_packet);
  30. }
  31. [Benchmark]
  32. public void Serialize_10000_Messages()
  33. {
  34. for (var i = 0; i < 10000; i++)
  35. {
  36. _serializer.Serialize(_packet);
  37. }
  38. }
  39. [Benchmark]
  40. public void Deserialize_10000_Messages()
  41. {
  42. for (var i = 0; i < 10000; i++)
  43. {
  44. using (var headerStream = new MemoryStream(Join(_serializedPacket)))
  45. {
  46. var header = MqttPacketReader.ReadHeaderAsync(new TestMqttChannel(headerStream), CancellationToken.None).GetAwaiter().GetResult();
  47. using (var bodyStream = new MemoryStream(Join(_serializedPacket), (int)headerStream.Position, header.BodyLength))
  48. {
  49. _serializer.Deserialize(header, bodyStream);
  50. }
  51. }
  52. }
  53. }
  54. private static byte[] Join(params ArraySegment<byte>[] chunks)
  55. {
  56. var buffer = new MemoryStream();
  57. foreach (var chunk in chunks)
  58. {
  59. buffer.Write(chunk.Array, chunk.Offset, chunk.Count);
  60. }
  61. return buffer.ToArray();
  62. }
  63. }
  64. }