Utf8Decode.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #region Copyright notice and license
  2. // Copyright 2019 The gRPC Authors
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #endregion
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Text;
  19. using BenchmarkDotNet.Attributes;
  20. using Grpc.Core.Internal;
  21. namespace Grpc.Microbenchmarks
  22. {
  23. [ClrJob, CoreJob] // test .NET Core and .NET Framework
  24. [MemoryDiagnoser] // allocations
  25. public class Utf8Decode
  26. {
  27. [Params(0, 1, 4, 128, 1024)]
  28. public int PayloadSize
  29. {
  30. get { return payloadSize; }
  31. set
  32. {
  33. payloadSize = value;
  34. payload = Invent(value);
  35. }
  36. }
  37. private int payloadSize;
  38. private byte[] payload;
  39. static byte[] Invent(int length)
  40. {
  41. var rand = new Random(Seed: length);
  42. var chars = new char[length];
  43. for(int i = 0; i < chars.Length; i++)
  44. {
  45. chars[i] = (char)rand.Next(32, 300);
  46. }
  47. return Encoding.UTF8.GetBytes(chars);
  48. }
  49. const int Iterations = 1000;
  50. [Benchmark(OperationsPerInvoke = Iterations)]
  51. public unsafe void Decode()
  52. {
  53. fixed (byte* ptr = payload)
  54. {
  55. var iPtr = new IntPtr(ptr);
  56. for (int i = 0; i < Iterations; i++)
  57. {
  58. MarshalUtils.PtrToStringUTF8(iPtr, payload.Length);
  59. }
  60. }
  61. }
  62. }
  63. }