Skip to content

Commit

Permalink
CSHARP-5368: Eliminiate allocations in Bson.Decimal128 to decimal con…
Browse files Browse the repository at this point in the history
…version (#1515)

Co-authored-by: Ferdinando Papale <4850119+papafe@users.noreply.github.com>
  • Loading branch information
obligaron and papafe authored Nov 26, 2024
1 parent 2decc43 commit 5edf5ba
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions src/MongoDB.Bson/ObjectModel/Decimal128.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1465,7 +1465,12 @@ private Decimal128(ulong highBits, ulong lowBits)
/// <param name="value">The value.</param>
public Decimal128(decimal value)
{
#if NET6_0_OR_GREATER
Span<int> bits = stackalloc int[4];
_ = decimal.GetBits(value, bits);
#else
var bits = decimal.GetBits(value);
#endif
var isNegative = (bits[3] & 0x80000000) != 0;
var scale = (short)((bits[3] & 0x00FF0000) >> 16);
var exponent = (short)-scale;
Expand Down Expand Up @@ -1904,7 +1909,12 @@ public int Compare(Decimal128 x, Decimal128 y)
{
var xType = GetDecimal128Type(x);
var yType = GetDecimal128Type(y);
var result = xType.CompareTo(yType);
// .NET Framework lacks some optimizations for enums that would result in boxing and lookup overhead for the default comparer
#if NET6_0_OR_GREATER
var result = Comparer<Decimal128Type>.Default.Compare(xType, yType);
#else
var result = ((int)xType).CompareTo((int)yType);
#endif
if (result == 0 && xType == Decimal128Type.Number)
{
return CompareNumbers(x, y);
Expand All @@ -1928,7 +1938,12 @@ private int CompareNumbers(Decimal128 x, Decimal128 y)
{
var xClass = GetNumberClass(x);
var yClass = GetNumberClass(y);
var result = xClass.CompareTo(yClass);
// .NET Framework lacks some optimizations for enums that would result in boxing and lookup overhead for the default comparer
#if NET6_0_OR_GREATER
var result = Comparer<NumberClass>.Default.Compare(xClass, yClass);
#else
var result = ((int)xClass).CompareTo((int)yClass);
#endif
if (result == 0)
{
if (xClass == NumberClass.Negative)
Expand Down

0 comments on commit 5edf5ba

Please sign in to comment.