DuckDB.NET 1.5.6.1: 128-bit Values Up to 6.6× Faster

Nov 23, 2026·
Giorgi Dalakishvili
Giorgi Dalakishvili
· 22 min read
blog Database

Introduction

DuckDB.NET, the .NET client for the DuckDB in-process analytical database, reads a HUGEINT column as long 6.6 times as fast in version 1.5.6.1 as in 1.5.6, because the value no longer goes through BigInteger, and a UUID column as Guid 3.3 times as fast. DECIMAL columns of more than 18 digits are read 1.7 times as fast, and a million rows of them now allocate almost nothing instead of 105 MB. Reading HUGEINT values as BigInteger is up to 3.9 times as fast.

On the write side, appending BigInteger values to HUGEINT columns is up to 3.5 times as fast, with 93 KB of allocations instead of 308 MB, and appending decimal values to a DECIMAL(38,10) column is 2.3 times as fast. For narrower DECIMAL columns the gain is smaller on Linux than on Windows, and one case, values that use all 28 digits of a decimal, got slower. DuckDB.NET 2.0 makes both faster.

This is part 3 of a series. Part 1 covers reading data, and part 2 covers appending and dates. As in the previous parts, none of this comes from DuckDB itself. Every benchmark runs DuckDB.NET 1.5.6 and 1.5.6.1 against the same DuckDB 1.5.6 engine, so the difference is the .NET code alone.

Table of Contents

The results

The benchmarks ran with BenchmarkDotNet and .NET 10 on the same Linux virtual machine as in the previous posts, an Azure F8as_v7 with an AMD EPYC 9V45 (Zen 5). Part 1 describes how they were run. The speedup is the range across all the benchmarks of a feature. The times and allocations are for the one benchmark in the Example column.

FeatureSpeedupExample1.5.6 time1.5.6.1 time1.5.6 allocated1.5.6.1 allocated
Reading UUIDs3.3×1M rows, four UUID columns as Guid98.6 ms29.6 ms17 KB17 KB
Reading HUGEINT as long6.6×1M rows, four HUGEINT columns82.3 ms12.5 ms17 KB17 KB
Reading HUGEINT as BigInteger2.2–3.9×1M rows, four HUGEINT columns of values above 64 bits166.1 ms43.0 ms427 MB153 MB
Reading decimals1.7–2.3×1M rows, four DECIMAL(38,4) columns271.4 ms157.9 ms105 MB17 KB
Appending decimals0.94–2.3×1M rows, four DECIMAL(38,10) columns193.8 ms84.6 ms147 MB139 KB
Appending HUGEINT from BigInteger1.9–3.5×1M rows, four HUGEINT columns of values above 64 bits246.3 ms70.2 ms308 MB93 KB
Control: a path that did not change1.0×1M rows, four TIME columns from TimeOnly53.2 ms52.1 ms93 KB93 KB
Control: work done by DuckDB1.0×Reading 1M rows without their values4.05 ms4.09 ms18 KB18 KB

The tables that follow one change at a time come from a second run on the same machine, which measures every commit against the one before it. Its times are a little different from the table above, so compare the rows within one table.

How DuckDB stores 128-bit values

DuckDB has three types that can take 128 bits. A HUGEINT is a signed 128-bit integer, and DuckDB’s C API hands it out as two 64-bit halves:

typedef struct {
  uint64_t lower;
  int64_t upper;
} duckdb_hugeint;

DuckDB.NET reads it as the DuckDBHugeInt struct, which has the same two fields. A UUID is stored as a HUGEINT too. The 32 hex digits of a UUID’s text are the digits of a 128-bit number, and DuckDB stores that number with its top bit flipped, so that sorting the integers sorts the UUIDs in the order of their text. A DECIMAL is stored as an integer, the value multiplied by 10 to the power of the column’s scale, so 12.3456 in a DECIMAL(18,4) column is stored as 123456. The width of the column decides how big that integer is. Up to 4 digits it’s a 16-bit integer, up to 9 a 32-bit one, up to 18 a 64-bit one, and a DECIMAL of 19 to 38 digits, which I’ll call a wide DECIMAL in this post, is stored as a HUGEINT.

So a UUID, a HUGEINT and a wide DECIMAL are all read from and written to the same 16 bytes. .NET has a type for exactly this since .NET 7, Int128, but DuckDB.NET 1.5.6 went through BigInteger or through bytes in most of these paths. Let’s see what that cost.

Reading UUIDs

In DuckDB.NET 1.5.6, a UUID was converted to a Guid like this:

// DuckDB.NET 1.5.6, GuidConverter
private const int GuidSize = 16;

// First 4 bytes (little-endian), Next 4 bytes (little-endian), Last 8 bytes (big-endian)
private static readonly int[] GuidByteOrder = [6, 7, 4, 5, 0, 1, 2, 3, 15, 14, 13, 12, 11, 10, 9, 8];

public static Guid ConvertToGuid(this DuckDBHugeInt input)
{
  Span<byte> bytes = stackalloc byte[32];

  // Reverse the bit flip on the upper 64 bits
  var upper = input.Upper ^ ((long)1 << 63);

  BitConverter.TryWriteBytes(bytes[GuidSize..], upper);
  BitConverter.TryWriteBytes(bytes[(GuidSize + 8)..], input.Lower);

  // Reconstruct the Guid bytes (reverse the original byte reordering)
  for (var i = 0; i < GuidSize; i++)
  {
    bytes[GuidByteOrder[i]] = bytes[i + GuidSize];
  }

  return new Guid(bytes[..GuidSize]);
}

The method writes both halves into a 32-byte buffer on the stack, moves the 16 bytes one at a time to the positions in the GuidByteOrder table, and builds the Guid from the first half of the buffer. The stackalloc and the loop also keep the method out of the JIT’s usual tiers. A method with a loop and a stackalloc is compiled once, fully optimized but without the profile data that Tier1 code gets, and it’s never inlined into ReadGuid. On .NET 10.0.14, x64, Linux, it reserves 80 bytes on the stack and clears 48 of them on every call.

The two halves already hold everything a Guid is made of. The upper half holds the first three groups of the UUID’s text (8, 4 and 4 hex digits) and the lower half the last two. Those are the parts that the Guid(int, short, short, byte, ...) constructor takes, so DuckDB.NET 1.5.6.1 passes them to it with shifts:

// DuckDB.NET 1.5.6.1, GuidConverter
public static Guid ConvertToGuid(this DuckDBHugeInt input)
{
  // Reverse the bit flip on the upper 64 bits
  var upper = input.Upper ^ ((long)1 << 63);
  var lower = input.Lower;

  return new Guid((int)(upper >> 32), (short)(upper >> 16), (short)upper,
    (byte)(lower >> 56), (byte)(lower >> 48), (byte)(lower >> 40), (byte)(lower >> 32),
    (byte)(lower >> 24), (byte)(lower >> 16), (byte)(lower >> 8), (byte)lower);
}

The new code needs neither the buffer nor the GuidByteOrder table, so the method has no stack frame at all, and the JIT inlines it into ReadGuid. Reading 4M UUIDs (1 million rows of 4 columns) went from 103.7 to 31.5 ms, so reading UUIDs is 3.3 times as fast:

MethodJobMeanRatioRatioSD
ReadGuids1-1.5.6106.00 ms1.000.06
ReadGuids2-2ab2ec7103.74 ms0.980.04
ReadGuids3-bd2b48e31.45 ms0.300.01

Reading HUGEINT values

In DuckDB.NET 1.5.6, every read of a HUGEINT column made a BigInteger first, whatever type the caller asked for. Reading the column as long looked like this:

// DuckDB.NET 1.5.6, NumericVectorDataReader
private T GetBigInteger<T>(ulong offset, bool unsigned)
{
  var bigInteger = GetBigInteger(offset, unsigned);   // hugeInt->ToBigInteger()

  try
  {
    return ConvertNumeric<BigInteger, T>(bigInteger);
  }
  catch (OverflowException)
  {
    throw new InvalidCastException($"Cannot cast from {nameof(BigInteger)} to {typeof(T).Name} in column {ColumnName}");
  }
}

// DuckDB.NET 1.5.6, DuckDBHugeInt
private static readonly BigInteger Base = BigInteger.Pow(2, 64);

public BigInteger ToBigInteger()
{
  return Upper * Base + Lower;
}

ToBigInteger converts both halves to BigInteger, multiplies the upper half by 2^64 and adds the lower half. For a value that needs more than 64 bits, the multiplication and the addition each allocate a new array for their result. Then ConvertNumeric checks that the BigInteger fits in a long and converts it back. Reading a HUGEINT as long is common, because DuckDB returns the sum of an integer column as a HUGEINT, so SELECT sum(amount) read with GetInt64 took this path.

As integers, through Int128

A HUGEINT is a 128-bit integer, which corresponds to Int128 in .NET. DuckDB.NET 1.5.6.1 builds an Int128 from the two halves and converts it the same way as every other integer column:

// DuckDB.NET 1.5.6.1, BigIntegerVectorDataReader
private T GetHugeInt<T>(ulong offset)
{
  var value = GetFieldData<DuckDBHugeInt>(offset);

  if (typeof(T) == typeof(BigInteger))
  {
    return (T)(object)value.ToBigInteger();
  }

  try
  {
    return NumericConverter.Convert<Int128, T>(value.ToInt128());
  }
  catch (OverflowException)
  {
    throw CannotCast(DuckDBType.ToString(), typeof(T));
  }
}

A BigInteger is now made only when the caller asks for a BigInteger. For a long, the range check is a comparison of the upper half with the sign of the lower half. On .NET 10.0.14, x64, Linux, the Tier1 code of GetHugeInt<long> looks like this (edited for brevity):

; DuckDB.NET 10b8478, BigIntegerVectorDataReader.GetHugeInt<long>
  shl      rsi, 4                           ; offset * 16
  add      rsi, qword ptr [rdi+0x30]        ; plus the vector's data pointer
  mov      rax, qword ptr [rsi]             ; lower
  mov      rcx, qword ptr [rsi+0x08]        ; upper
  mov      rdx, rax
  sar      rdx, 63                          ; what upper is for a value that fits a long: 0 or -1
  cmp      rcx, rdx
  je       SHORT G_M000_IG05                ; it fits: return lower
  call     [System.ThrowHelper:ThrowOverflowException()]

The whole read is the two loads and that comparison, and nothing is called unless the value doesn’t fit. Reading 4M HUGEINT values as long went from 72.2 to 13.3 ms with this change. The row before it already has the plain virtual methods from part 1, and with both changes, the read is 6.6 times as fast as in 1.5.6:

MethodJobMeanMedianRatioRatioSD
ReadHugeIntsAsLong1-1.5.689.15 ms88.16 ms1.000.04
ReadHugeIntsAsLong2-f7db22b71.87 ms72.17 ms0.810.03
ReadHugeIntsAsLong3-10b847813.37 ms13.32 ms0.150.00

As BigInteger

The same change made reading a HUGEINT as BigInteger faster too. GetHugeInt<BigInteger> now builds the Int128 and converts it to BigInteger in one step, instead of going through the multiplication and the addition in ToBigInteger. Reading 4M values of up to 64 bits went from 79.3 to 36.4 ms. Values above 64 bits went from 170.7 to 49.1 ms, and their allocations from 427 MB to 153 MB. A BigInteger keeps a value that fits in an int in a field and a bigger one in an array, so the 153 MB left are the arrays of the 4M values the benchmark reads, which every BigInteger of that size needs:

MethodJobMeanMedianRatioAllocatedAlloc Ratio
ReadHugeIntsAsBigInteger1-1.5.684.25 ms84.55 ms1.0017.07 KB1.00
ReadHugeIntsAsBigInteger2-f7db22b78.99 ms79.34 ms0.9417.08 KB1.00
ReadHugeIntsAsBigInteger3-10b847835.77 ms36.35 ms0.4217.01 KB1.00
ReadLargeHugeIntsAsBigInteger1-1.5.6179.52 ms176.56 ms1.00437,523.27 KB1.00
ReadLargeHugeIntsAsBigInteger2-f7db22b170.20 ms170.70 ms0.95437,523.30 KB1.00
ReadLargeHugeIntsAsBigInteger3-10b847849.24 ms49.10 ms0.27156,269.63 KB0.36

GetValue, which Dapper uses, goes another way. It still made its BigInteger with ToBigInteger, and so did the wide DECIMAL read, so the next change moved the conversion into ToBigInteger itself:

// DuckDB.NET 1.5.6.1, DuckDBHugeInt
public BigInteger ToBigInteger()
{
  return new Int128((ulong)Upper, Lower);   // the implicit conversion from Int128 to BigInteger
}

With it, reading 4M values with GetValue went from 83.2 to 39.8 ms. It still allocates 122 MB, because GetValue returns an object, so every BigInteger is boxed:

MethodJobMeanMedianRatioAllocatedAlloc Ratio
ReadHugeIntsAsObject1-1.5.684.69 ms85.20 ms1.00125,019.27 KB1.00
ReadHugeIntsAsObject4-d33310584.87 ms83.21 ms1.00125,019.30 KB1.00
ReadHugeIntsAsObject5-9410c2a39.72 ms39.79 ms0.47125,019.29 KB1.00

In DuckDB.NET 2.0, Int128 is the default type for HUGEINT columns, so GetValue returns an Int128, and GetFieldValue<BigInteger> still gives you a BigInteger.

Reading decimals

A DECIMAL of up to 18 digits fits in a long, and so does the integer part of a decimal, which has 96 bits for it. For these columns, DuckDB.NET 1.5.6 built the decimal directly from the stored integer and the scale. A wider DECIMAL went through BigInteger:

// DuckDB.NET 1.5.6, DecimalVectorDataReader
private decimal GetDecimal(ulong offset)
{
  switch (decimalType)
  {
    case DuckDBType.SmallInt:
      ...
    case DuckDBType.BigInt:
      {
        var raw = GetFieldData<long>(offset);
        var abs = (ulong)Math.Abs(raw);
        return new decimal((int)abs, (int)(abs >> 32), 0, raw < 0, Scale);
      }
    case DuckDBType.HugeInt:
      {
        var hugeInt = numericVectorDataReader.GetBigInteger(offset, false);   // ToBigInteger

        var quotient = BigInteger.DivRem(hugeInt, DecimalExtensions.BigIntPowersOfTen[Scale], out var remainder);

        try
        {
          var result = (decimal)quotient;
          result += decimal.Divide((decimal)remainder, DecimalExtensions.PowersOfTen[Scale]);
          return result;
        }
        catch (OverflowException exception)
        {
          throw new OverflowException($"Value in column {ColumnName} exceeds the range of System.Decimal. ...", exception);
        }
      }
    default: throw new DuckDBException($"Invalid storage type {decimalType} ({(int)decimalType}) for decimal column {ColumnName}");
  }
}

For every value of a wide column, the reader made a BigInteger with ToBigInteger, then divided it by 10 to the power of the scale with BigInteger.DivRem, which makes two more. Then it converted the quotient and the remainder to decimal and added them.

Wide decimals without BigInteger

The new ToBigInteger from the previous section already halved the allocations of this read, from 105 MB to 52 MB. It also took the read from 291.5 to 191.0 ms. The rest of the BigInteger values go away when the stored value is divided as an Int128:

// DuckDB.NET 2ab2ec7, DecimalVectorDataReader.GetDecimal
case DuckDBType.HugeInt:
  {
    var raw = GetFieldData<DuckDBHugeInt>(offset);

    var (quotient, remainder) = Int128.DivRem(new Int128((ulong)raw.Upper, raw.Lower), DecimalExtensions.Int128PowersOfTen[Scale]);

    try
    {
      var result = (decimal)quotient;
      result += decimal.Divide((decimal)remainder, DecimalExtensions.PowersOfTen[Scale]);
      return result;
    }
    ...
  }

With the division on Int128, reading 4M wide decimals allocates nothing, and the read went down to 133.0 ms, about 2.2 times as fast as in 1.5.6:

MethodJobMeanMedianRatioAllocatedAlloc Ratio
ReadWideDecimals1-1.5.6297.22 ms291.53 ms1.00107,123.86 KB1.000
ReadWideDecimals2-9410c2a192.03 ms190.96 ms0.6553,570.68 KB0.500
ReadWideDecimals3-2ab2ec7132.50 ms133.01 ms0.4517.39 KB0.000

The cost of a large stack frame

The division and the try block need room on the stack, for the Int128 and decimal values they work with. All of them live in the stack frame of GetDecimal, and C# compiles every method with the localsinit flag, which tells the JIT that locals start at zero. For a local that the JIT keeps in a register, that costs nothing. A struct that lives on the stack is cleared in the method’s prolog, before the first line of the method runs, on every call. That includes the calls that read a DECIMAL(18,4) column and return from the BigInt case without touching any of these locals. On .NET 10.0.14, x64, Linux, the prolog of GetDecimal looks like this (edited for brevity):

; DuckDB.NET 2ab2ec7, DecimalVectorDataReader.GetDecimal
  push     rbp
  ...                                       ; five more registers saved
  sub      rsp, 312                         ; reserve 312 bytes
  lea      rbp, [rsp+0x160]
  vxorps   xmm8, xmm8, xmm8
  vmovdqu  ymmword ptr [rbp-0xD0], ymm8     ; clear 32 bytes
  vmovdqu  ymmword ptr [rbp-0xB0], ymm8     ; and 32 more
  vmovdqu  ymmword ptr [rbp-0x90], ymm8
  vmovdqu  ymmword ptr [rbp-0x70], ymm8
  vmovdqu  ymmword ptr [rbp-0x50], ymm8
  xor      eax, eax
  mov      qword ptr [rbp-0x30], rax        ; 168 bytes cleared
  mov      eax, dword ptr [rdi+0x3C]        ; only now: the storage type
  lea      ebx, [rax-0x03]
  cmp      ebx, 2
  jbe      G_M000_IG18                      ; SmallInt, Integer or BigInt

The method clears these 168 bytes before it even looks at the storage type, so reading a DECIMAL(18,4) column pays for them too, although that read needs none of them.

The fix moves the wide case into a method of its own, so its locals live in the frame of that method:

// DuckDB.NET 495269d, DecimalVectorDataReader
private decimal GetDecimal(ulong offset)
{
  switch (decimalType)
  {
    ...
    case DuckDBType.BigInt:
      {
        var raw = GetFieldData<long>(offset);
        var abs = (ulong)Math.Abs(raw);
        return new decimal((int)abs, (int)(abs >> 32), 0, raw < 0, Scale);
      }
    case DuckDBType.HugeInt:
      return GetWideDecimal(offset);
    default: throw InvalidStorageType();
  }
}

// A DECIMAL of more than 18 digits, which DuckDB stores as a HUGEINT
private decimal GetWideDecimal(ulong offset)
{
  var raw = GetFieldData<DuckDBHugeInt>(offset);

  var (quotient, remainder) = Int128.DivRem(new Int128((ulong)raw.Upper, raw.Lower), DecimalExtensions.Int128PowersOfTen[Scale]);
  ...
}

The exception for an unknown storage type moved to InvalidStorageType, because building its message needs room on the stack too. The prolog of GetDecimal is now four instructions, and nothing is cleared:

; DuckDB.NET 495269d, DecimalVectorDataReader.GetDecimal
  push     rbp
  push     rbx
  sub      rsp, 88                          ; reserve 88 bytes, clear nothing
  lea      rbp, [rsp+0x60]
  mov      eax, dword ptr [rdi+0x3C]        ; the storage type
  lea      ebx, [rax-0x03]
  cmp      ebx, 2
  jbe      SHORT G_M000_IG04                ; SmallInt, Integer or BigInt
  cmp      eax, 16
  jne      SHORT G_M000_IG05                ; not HugeInt: InvalidStorageType
  call     [DecimalVectorDataReader:GetWideDecimal(ulong):System.Decimal:this]   ; the wide case
  ...

Reading 4M DECIMAL(18,4) values went from 29.0 to 26.4 ms, about 9% less time. The same change made the wide decimals slower, from 133.0 to 164.3 ms, and in 1.5.6.1 they take 169.6 ms. GetWideDecimal clears 80 bytes of its own frame on every call, and on Linux the decimal it returns goes through the stack on its way back to GetDecimal, which part 5 looks at. Reading wide decimals is still 1.7 times as fast as in 1.5.6, but slower than right after the Int128 division:

MethodJobMeanMedianRatioRatioSD
ReadDecimals1-1.5.666.05 ms62.61 ms1.020.18
ReadDecimals3-2ab2ec729.02 ms29.00 ms0.450.05
ReadDecimals4-495269d26.43 ms26.37 ms0.410.05
ReadDecimals5-1.5.6.126.88 ms26.95 ms0.410.05
ReadWideDecimals1-1.5.6297.22 ms291.53 ms1.000.06
ReadWideDecimals3-2ab2ec7132.50 ms133.01 ms0.450.02
ReadWideDecimals4-495269d165.28 ms164.32 ms0.560.03
ReadWideDecimals5-1.5.6.1170.23 ms169.57 ms0.570.03

The times of 1.5.6 for DECIMAL(18,4) vary a lot from one iteration to the next, so the median is the number to look at for that row.

Appending decimals

The appender in DuckDB.NET 1.5.6 wrote a decimal to a DECIMAL column with System.Decimal arithmetic:

// DuckDB.NET 1.5.6, DecimalVectorDataWriter
internal override bool AppendDecimal(decimal value, ulong rowIndex)
{
  switch (decimalType)
  {
    case DuckDBType.SmallInt:
      AppendValueInternal((short)decimal.Multiply(value, DecimalExtensions.PowersOfTen[targetColumnScale]), rowIndex);
      break;
    ...
    case DuckDBType.BigInt:
      AppendValueInternal((long)decimal.Multiply(value, DecimalExtensions.PowersOfTen[targetColumnScale]), rowIndex);
      break;
    case DuckDBType.HugeInt:
      var mantissa = value.GetMantissa();   // a BigInteger

      // Rescale: mantissa is value × 10^valueScale, DuckDB needs value × 10^targetColumnScale.
      if (targetColumnScale > value.Scale)
        mantissa *= DecimalExtensions.BigIntPowersOfTen[targetColumnScale - value.Scale];
      else if (targetColumnScale < value.Scale)
        mantissa /= DecimalExtensions.BigIntPowersOfTen[value.Scale - targetColumnScale];

      AppendValueInternal(new DuckDBHugeInt(mantissa), rowIndex);
      break;
  }

  return true;
}

For a column of up to 18 digits, the value is multiplied by 10 to the power of the column’s scale, as a decimal, and the product is cast to an integer. For a wide column, the integer of the decimal becomes a BigInteger, which is multiplied or divided by a BigInteger power of ten and then handed to the DuckDBHugeInt constructor.

Integer arithmetic instead of System.Decimal

A decimal is a 96-bit integer, a sign and a scale. 12.34 is the integer 1234 with a scale of 2. Writing it to a DECIMAL(18,4) column means turning 1234 with a scale of 2 into 123400, the integer for a scale of 4. That’s a multiplication of the integer by 10^2, which plain integer arithmetic can do. DuckDB.NET 1.5.6.1 takes the parts of the decimal out and does the arithmetic on integers:

// DuckDB.NET 1.5.6.1, DecimalVectorDataWriter
internal override bool AppendDecimal(decimal value, ulong rowIndex)
{
  value.GetParts(out var low, out var high, out var isNegative, out var valueScale);

  var powers = DecimalExtensions.UInt64PowersOfTen;
  var shift = scale - valueScale;

  // The integer needs more than 64 bits, or the scales are 20 or more apart
  if (high != 0 || Math.Abs(shift) >= powers.Length)
  {
    return AppendLongDecimal(value, rowIndex);
  }

  // The rescaled integer in two halves of 64 bits. Only a multiplication can fill the upper half.
  ulong lower, upper = 0;

  if (shift >= 0)
  {
    upper = Math.BigMul(low, powers[shift], out lower);
  }
  else
  {
    lower = low / powers[-shift];
  }

  if (upper > limitUpper || (upper == limitUpper && lower >= limitLower))
  {
    throw DoesNotFit(value);
  }

  return Store(lower, upper, isNegative, rowIndex);
}

Every value of up to 19 digits has an integer that fits in 64 bits, so for these values the rescaling is one Math.BigMul, which the JIT compiles to a single mulx instruction, or one division. Store then writes the integer in the column’s storage size, as a 16-, 32- or 64-bit integer, or as the two halves of a HUGEINT. Any other value goes to AppendLongDecimal, which does the same steps on UInt128, so no value goes through BigInteger any more.

For a DECIMAL(38,10) column, appending 4M decimals took 225.5 ms in 1.5.6, with 147 MB of allocations. The new DuckDBHugeInt constructor from the last section of this post came before this change and already brought it down to 164.2 ms and 122 MB. With the integer arithmetic, it takes 95.6 ms and allocates 139 KB, so appending to a wide column is 2.4 times as fast as in 1.5.6:

MethodJobMeanRatioAllocatedAlloc Ratio
AppendToWide1-1.5.6225.52 ms1.00150,132.63 KB1.000
AppendToWide2-ece99eb164.15 ms0.73125,108.13 KB0.833
AppendToWide3-2e922d795.64 ms0.43138.69 KB0.001
AppendToWide4-1.5.6.192.61 ms0.41138.69 KB0.001

A gain that depends on the OS

When I measured this change on my laptop, on Windows, appending decimals to a DECIMAL(18,4) column was about twice as fast as before it. On the Linux machine that all the numbers in this post come from, the same change takes appending 4M decimals from 91.1 to 79.6 ms, which is only 13% less time. In 1.5.6.1, with the changes that came after it, it takes 72.0 ms, so appending decimals to columns of up to 18 digits is 1.3 times as fast as in 1.5.6:

MethodJobMeanRatioRatioSD
AppendSameScale1-1.5.697.06 ms1.000.06
AppendSameScale2-ece99eb91.14 ms0.940.04
AppendSameScale3-2e922d779.61 ms0.820.06
AppendSameScale4-1.5.6.171.97 ms0.740.04
AppendSmallerScale1-1.5.696.37 ms1.000.05
AppendSmallerScale2-ece99eb90.42 ms0.940.04
AppendSmallerScale3-2e922d777.64 ms0.810.05
AppendSmallerScale4-1.5.6.174.35 ms0.770.04

At first I thought the difference came from the CPU, because the laptop has an Intel CPU and the virtual machine an AMD one. Running the same code on the same laptop under Linux showed the small gain too, so it comes from the operating system. The difference is in how a decimal is passed to a method, which is set by the operating system’s calling convention, not by C#. On Windows x64, the caller puts a copy of a 16-byte struct such as decimal in memory and passes a pointer to it, so AppendDecimal reads its fields from memory. On Linux x64, the struct is passed in two registers. The new code takes the parts of the decimal out with GetParts:

// DuckDB.NET 1.5.6.1, DecimalExtensions
internal void GetParts(out ulong low, out uint high, out bool isNegative, out byte scale)
{
  Span<int> bits = stackalloc int[4];
  decimal.GetBits(value, bits);

  low = (uint)bits[0] | (ulong)(uint)bits[1] << 32;
  high = (uint)bits[2];
  isNegative = bits[3] < 0;
  scale = (byte)(bits[3] >> 16);
}

On Linux, the JIT first stores the two registers on the stack and reads them back as one 16-byte value, and only then copies the fields into the buffer. The CPU can’t hand a value from two smaller stores in flight to one larger load, so it waits for the stores to finish. On Windows, the fields are read through the pointer and go into the buffer as four 4-byte values, and each of them is read back at the same size, which the CPU can do without waiting. The detail of that wait is the subject of part 5, together with the other places where it showed up in this series. DuckDB.NET 2.0 reads the parts of a decimal without the round trip through the stack.

28 digits: a division in software

The one benchmark that got slower is AppendQuotients, which appends values such as 1001m / 7m to a DECIMAL(18,4) column. These values use all 28 digits a decimal has, most of them after the point, so the integer of every value has to be divided by a power of ten above 10^20. In 1.5.6, decimal.Multiply did this rescaling inside the runtime’s own decimal code. In 1.5.6.1, the integer of such a value needs more than 64 bits, so it goes to AppendLongDecimal and is divided as a UInt128. That power of ten doesn’t fit in 64 bits either, and for such a divisor .NET’s UInt128 division falls back to a long division written in C#. Appending 4M of these values went from 161.7 to 175.1 ms with the change, and in 1.5.6.1 it takes 178.3 ms, slower than in 1.5.6:

MethodJobMeanRatioRatioSD
AppendQuotients1-1.5.6173.11 ms1.000.03
AppendQuotients2-ece99eb161.71 ms0.930.02
AppendQuotients3-2e922d7175.12 ms1.010.03
AppendQuotients4-1.5.6.1178.29 ms1.030.06

AppendLongDecimal has the same 16-byte round trip on Linux as AppendDecimal, so this case pays for both. DuckDB.NET 2.0 removes the round trip here too.

Appending HUGEINT values from BigInteger

Appending a BigInteger to a HUGEINT column goes through the DuckDBHugeInt constructor, which splits the value into its two halves. In DuckDB.NET 1.5.6 it did that with a division:

// DuckDB.NET 1.5.6, DuckDBHugeInt
private static readonly BigInteger Base = BigInteger.Pow(2, 64);

public DuckDBHugeInt(BigInteger value)
{
  if (value < HugeIntMinValue || value > HugeIntMaxValue)
  {
    throw new ArgumentOutOfRangeException(nameof(value), $"value must be between {HugeIntMinValue} and {HugeIntMaxValue}");
  }

  var upper = (long)BigInteger.DivRem(value, Base, out var rem);

  if (rem < 0)
  {
    rem += Base;
    upper -= 1;
  }

  Upper = upper;
  Lower = (ulong)rem;
}

BigInteger.DivRem makes a new BigInteger for the quotient and another one for the remainder, and a negative remainder makes a third. The two halves of an Int128 are the two halves of a HUGEINT, sign included, so DuckDB.NET 1.5.6.1 converts the value to Int128 and takes them from there:

// DuckDB.NET 1.5.6.1, DuckDBHugeInt
public DuckDBHugeInt(BigInteger value)
{
  if (value < HugeIntMinValue || value > HugeIntMaxValue)
  {
    throw new ArgumentOutOfRangeException(nameof(value), $"value must be between {HugeIntMinValue} and {HugeIntMaxValue}");
  }

  // The two halves of the Int128 are the two halves of the HUGEINT, the sign included.
  var wide = (Int128)value;

  Upper = (long)(wide >> 64);
  Lower = (ulong)wide;
}

The conversion reads the digits of the BigInteger and allocates nothing. Appending 4M BigInteger values that fit in an int went from 132.8 to 74.9 ms. Values above 2^126 went from 281.2 to 82.9 ms. In both cases the allocations went down to 93 KB, from 59 MB and 308 MB, so appending BigInteger values is 1.9 to 3.5 times as fast as in 1.5.6:

MethodJobMeanRatioAllocatedAlloc Ratio
AppendSmallToHugeInt1-1.5.6140.33 ms1.0060,884.22 KB1.000
AppendSmallToHugeInt2-495269d132.76 ms0.9560,884.22 KB1.000
AppendSmallToHugeInt3-dd5bb8a74.94 ms0.5392.84 KB0.002
AppendLargeToHugeInt1-1.5.6291.78 ms1.00315,277.34 KB1.000
AppendLargeToHugeInt2-495269d281.15 ms0.96315,277.34 KB1.000
AppendLargeToHugeInt3-dd5bb8a82.88 ms0.2892.84 KB0.000

What’s next

The next post covers scalar and table functions, and reading lists, structs and maps. Part 5 explains the wait that showed up three times in this series, in List<int?> in part 2 and in the wide decimal read and the decimal append in this post, and how to find such problems yourself. All the changes in this series are in DuckDB.NET 1.5.6.1 on NuGet, and they carry over to DuckDB.NET 2.0. To upgrade, run:

dotnet add package DuckDB.NET.Data.Full --version 1.5.6.1

DuckDB.NET.Data.Full includes the native DuckDB library. If you supply the library yourself, use DuckDB.NET.Data instead.

Giorgi Dalakishvili
Authors
Backend Engineer & Software Architect · 3x Microsoft MVP · International Speaker

I’m a backend engineer and software architect with 17+ years of .NET, mostly in banking and fintech: payment and transaction processing, public APIs, and the internal platforms other teams build on. I’ve led teams and a platform unit, and I stay hands-on in the code, increasingly through AI coding agents like Claude Code and Codex.

Alongside that, I build open-source .NET libraries and developer tools with 47M+ NuGet downloads: DuckDB.NET, EntityFramework.Exceptions, EFCore.Visualizer and others. That work sits where .NET meets the database: native interop, Native AOT extensions for DuckDB and PostgreSQL, and tooling that makes query plans easier to debug. I also speak about .NET and databases at conferences like NDC, KCDC and .NET Conf.