Uploaded image for project: 'C# Driver'
  1. C# Driver
  2. CSHARP-5368

Performance: Eliminiate allocations in Bson.Decimal128 to decimal conversion

    • Type: Icon: Improvement Improvement
    • Resolution: Unresolved
    • Priority: Icon: Unknown Unknown
    • None
    • Affects Version/s: 2.30.0, 3.0.0
    • Component/s: BSON, Performance
    • None
    • Dotnet Drivers

      When converting a System.Decimal to MongoDB.Bson.Decimal128, there are some allocations (enum-boxing and array allocation) that can be avoided.

      This can improve performance and reduce GC load, as shown in the benchmark below.

      Benchmark
       

          [BenchmarkCategory(DriverBenchmarkCategory.BsonBench), MemoryDiagnoser]
          public class BsonDecimalConversionBenchmark
          {
              Decimal128 _sourceBsonDecimal128;
              decimal _sourceSystemDecimal;
              RepresentationConverter _converter;        [GlobalSetup]
              public void Setup()
              {
                  _sourceSystemDecimal = 128m;
                  _sourceBsonDecimal128 = new Decimal128(128m);
                  _converter = new RepresentationConverter(allowOverflow: false, allowTruncation: true);
              }        [Benchmark]
              public void ConvertToBsonDecimal()
              {
                  _ = _converter.ToDecimal128(_sourceSystemDecimal);
              }        [Benchmark]
              public void ConvertFromBsonDecimal()
              {
                  _ = _converter.ToDecimal(_sourceBsonDecimal128);
              }
          } 

       
      Results in v3.0/main-branch

      .NET 8.0

      Method Mean Error StdDev Gen0 Allocated
      ConvertToBsonDecimal 10.48 ns 0.138 ns 0.122 ns 0.0024 40 B
      ConvertFromBsonDecimal 72.92 ns 0.588 ns 0.550 ns 0.0229 384 B

      .NET 4.81

      Method Mean Error StdDev Gen0 Allocated
      ConvertToBsonDecimal 20.47 ns 0.022 ns 0.019 ns 0.0063 40 B
      ConvertFromBsonDecimal 233.64 ns 0.403 ns 0.377 ns 0.0610 385 B

      Improved state

      .NET 8.0

      Method Mean Error StdDev Gen0 Allocated
      ConvertToBsonDecimal 9.138 ns 0.0165 ns 0.0154 ns - -
      ConvertFromBsonDecimal 23.974 ns 0.0343 ns 0.0304 ns - -

      .NET 4.81

      Method Mean Error StdDev Gen0 Allocated
      ConvertToBsonDecimal 21.10 ns 0.058 ns 0.045 ns 0.0063 40 B
      ConvertFromBsonDecimal 176.39 ns 0.651 ns 0.544 ns - -

       

       

       

            Assignee:
            ferdinando.papale@mongodb.com Ferdinando Papale
            Reporter:
            obligaron@live.com obligaron N/A
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated: