10000 CSHARP-5368: Eliminiate allocations in Bson.Decimal128 to decimal con… · mongodb/mongo-csharp-driver@5edf5ba · GitHub
[go: up one dir, main page]

Skip to content

Commit 5edf5ba

Browse files
obligaronpapafe
andauthored
CSHARP-5368: Eliminiate allocations in Bson.Decimal128 to decimal conversion (#1515)
Co-authored-by: Ferdinando Papale <4850119+papafe@users.noreply.github.com>
1 parent 2decc43 commit 5edf5ba

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

src/MongoDB.Bson/ObjectModel/Decimal128.cs

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1465,7 +1465,12 @@ private Decimal128(ulong highBits, ulong lowBits)
14651465
/// <param name="value">The value.</param>
14661466
public Decimal128(decimal value)
14671467
{
1468+
#if NET6_0_OR_GREATER
1469+
Span<int> bits = stackalloc int[4];
1470+
_ = decimal.GetBits(value, bits);
1471+
#else
14681472
var bits = decimal.GetBits(value);
1473+
#endif
14691474
var isNegative = (bits[3] & 0x80000000) != 0;
14701475
var scale = (short)((bits[3] & 0x00FF0000) >> 16);
14711476
var exponent = (short)-scale;
@@ -1904,7 +1909,12 @@ public int Compare(Decimal128 x, Decimal128 y)
19041909
{
19051910
var xType = GetDecimal128Type(x);
19061911
var yType = GetDecimal128Type(y);
1907-
var result = xType.CompareTo(yType);
1912+
// .NET Framework lacks some optimizations for enums that would result in boxing and lookup overhead for the default comparer
1913+
#if NET6_0_OR_GREATER
1914+
var result = Comparer<Decimal128Type>.Default.Compare(xType, yType);
1915+
#else
1916+
var result = ((int)xType).CompareTo((int)yType);
1917+
#endif
19081918
if (result == 0 && xType == Decimal128Type.Number)
19091919
{
19101920
return CompareNumbers(x, y);
@@ -1928,7 +1938,12 @@ private int CompareNumbers(Decimal128 x, Decimal128 y)
19281938
{
19291939
var xClass = GetNumberClass(x);
19301940
var yClass = GetNumberClass(y);
1931-
var result = xClass.CompareTo(yClass);
1941+
// .NET Framework lacks some optimizations for enums that would result in boxing and lookup overhead for the default comparer
1942+
#if NET6_0_OR_GREATER
1943+
var result = Comparer<NumberClass>.Default.Compare(xClass, yClass);
1944+
#else
1945+
var result = ((int)xClass).CompareTo((int)yClass);
1946+
#endif
19321947
if (result == 0)
19331948
{
19341949
if (xClass == NumberClass.Negative)

0 commit comments

Comments
 (0)
0