HexDecodeBenches.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Globalization;
  3. using BenchmarkDotNet.Attributes;
  4. using BenchmarkDotNet.Running;
  5. using MediaBrowser.Common;
  6. namespace Jellyfin.Common.Benches
  7. {
  8. [MemoryDiagnoser]
  9. public class HexDecodeBenches
  10. {
  11. private string _data;
  12. [Params(0, 10, 100, 1000, 10000, 1000000)]
  13. public int N { get; set; }
  14. [GlobalSetup]
  15. public void GlobalSetup()
  16. {
  17. var bytes = new byte[N];
  18. new Random(42).NextBytes(bytes);
  19. _data = Hex.Encode(bytes);
  20. }
  21. [Benchmark]
  22. public byte[] Decode() => Hex.Decode(_data);
  23. [Benchmark]
  24. public byte[] DecodeSubString() => DecodeSubString(_data);
  25. private static byte[] DecodeSubString(string str)
  26. {
  27. byte[] bytes = new byte[str.Length / 2];
  28. for (int i = 0; i < str.Length; i += 2)
  29. {
  30. bytes[i / 2] = byte.Parse(
  31. str.Substring(i, 2),
  32. NumberStyles.HexNumber,
  33. CultureInfo.InvariantCulture);
  34. }
  35. return bytes;
  36. }
  37. }
  38. }