DuckDB.NET 1.5.6.1: Scalar Functions Up to 7.7× Faster

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

Introduction

DuckDB.NET, the .NET client for the DuckDB in-process analytical database, runs scalar functions written in C# 5 to 7.7 times as fast in version 1.5.6.1 as in 1.5.6, and table functions 2.5 to 5.9 times as fast. A query that reads one of the four columns of a table function is 6.3 times as fast, and the columns it doesn’t read are no longer worked out at all. Reading LIST, STRUCT and MAP columns is up to 5.9 times as fast, and functions with a nullable argument or result, as well as table functions that return structs, allocate almost nothing any more.

This is part 4 of a series. Part 1 covers reading data, part 2 appending and dates, and part 3 128-bit values and decimals. 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
Typed scalar functions5.0–7.7×1M calls with an int? argument21.2 ms4.0 ms20.7 MB104 KB
Scalar function with a string argument1.6×1M calls, the length of a string29.4 ms18.4 ms38 MB38 MB
Table functions2.5–5.9×1M rows of four columns37.4 ms9.6 ms20.8 MB110 KB
Projection pushdown6.3×1M rows, one of four columns read18.7 ms2.95 ms97 KB40 KB
Reading LIST, STRUCT and MAP1.1–5.9×200k lists of int?31.1 ms5.3 ms45.8 MB18.3 MB
Control: work done by DuckDB1.0×SUM over 1M rows in SQL0.508 ms0.506 ms1.1 KB1.1 KB
Control: a table instead of a table function1.0×1M rows of one column0.378 ms0.376 ms1.4 KB1.3 KB

For the tables that follow one change at a time, I ran the benchmarks again on the same machine and measured every commit against the one before it. The times of that run are a little different from the table above, so compare the rows within one table. Most of these functions and reads also got faster from the changes in the previous posts, so each table has a row for the commit just before the changes of its section, which has all of those.

Scalar functions

How a typed function reads and writes its values

DuckDB.NET 1.5 added a simpler way to register a scalar function. You give it a lambda, and DuckDB.NET reads the arguments and writes the results for you:

connection.RegisterScalarFunction<int, int>("plus_one", value => value + 1);

DuckDB calls a scalar function once for every chunk of up to 2,048 rows, and DuckDB.NET then calls the lambda once for every row. In DuckDB.NET 1.5.6 it wrapped the lambda in a delegate for one row and a loop over the public reader and writer interfaces:

// DuckDB.NET 1.5.6, DuckDBConnectionScalarFunctionExtensions
public void RegisterScalarFunction<T, TResult>(string name, Func<T, TResult> func)
{
  var (nullability, anyNullable) = InferParameterNullability(func);

  connection.RegisterScalarFunction<T, TResult>(name, WrapScalarFunction<TResult>((readers, index) =>
    func(ReadValue<T>(readers[0], index, nullability[0], anyNullable))), new() { HandlesNulls = anyNullable });
}

private static Action<IReadOnlyList<IDuckDBDataReader>, IDuckDBDataWriter, ulong> WrapScalarFunction<TResult>(
  Func<IReadOnlyList<IDuckDBDataReader>, ulong, TResult> perRowFunc)
{
  return (readers, writer, rowCount) =>
  {
    for (ulong index = 0; index < rowCount; index++)
    {
      var result = perRowFunc(readers, index);

      writer.WriteValue(result, index);   // IDuckDBDataWriter.WriteValue<TResult>
    }
  };
}

private static T ReadValue<T>(IDuckDBDataReader reader, ulong index, bool isNullable, bool checksNulls)
{
  ...
  return typeof(T) == typeof(object) ? (T)reader.GetValue(index) : reader.GetValue<T>(index);   // IDuckDBDataReader.GetValue<T>
}

ReadValue calls GetValue<T> on an IDuckDBDataReader, and the loop calls WriteValue<T> on an IDuckDBDataWriter. Both are generic methods called through an interface, which is the generic virtual call from part 1. The runtime has to look up the code for the actual class and the type argument on every call, so every row of a function with one argument pays for two lookups. The commit just before the fix still has this code, so let’s see what the JIT generates for its loop. On .NET 10.0.12, x64, Linux, the Tier1 code looks like this (edited for brevity):

; DuckDB.NET 0407f4c, the loop of WrapScalarFunction<int>
  call     [r11]IReadOnlyList`1[__Canon]:get_Item(int)    ; readers[0], an interface call
  ...
  call     CORINFO_HELP_VIRTUAL_FUNC_PTR                  ; look up IDuckDBDataReader.GetValue<int>
  call     rax
  ...
  call     [rcx+0x18]System.Func`2[int,int]:Invoke(int)   ; the lambda
  ...
  call     CORINFO_HELP_VIRTUAL_FUNC_PTR                  ; look up IDuckDBDataWriter.WriteValue<int>
  call     rax
  inc      r12                                            ; next row

Besides the two lookups, every row makes an interface call to get the reader out of the list and calls the lambda through a delegate.

Calling the readers and the writer without generic virtual calls

The library doesn’t need the interfaces in its own loops, so I gave each typed overload a loop of its own, which gets the readers and the writer as the VectorDataReaderBase and VectorDataWriterBase classes:

// DuckDB.NET ee223da, DuckDBConnectionScalarFunctionExtensions
public void RegisterScalarFunction<T, TResult>(string name, Func<T, TResult> func)
{
  var (nullability, anyNullable) = InferParameterNullability(func);

  connection.RegisterScalarMethod(name, (readers, writer, rowCount) =>   // VectorDataReaderBase[], VectorDataWriterBase
  {
    var reader = readers[0];
    var nullable = nullability[0];

    for (ulong index = 0; index < rowCount; index++)
    {
      writer.WriteValue(func(ReadValue<T>(reader, index, nullable, anyNullable)), index);
    }
  }, LogicalType<TResult>(), varargs: false, new() { HandlesNulls = anyNullable }, LogicalType<T>());
}

GetValue<T> and WriteValue<T> aren’t virtual on these classes, so the JIT calls them directly and can inline them. The loop of plus_one now looks like this:

; DuckDB.NET ee223da, the loop of RegisterScalarFunction<int, int>
  cmp      qword ptr [r13+0x28], 0            ; does the argument have NULLs?
  jne      G_M000_IG10                        ; then check the row's validity bit
  mov      rdi, 0x72D160805240                ; typeof(int)
  cmp      gword ptr [r13+0x20], rdi          ; StorageType == typeof(int)?
  jne      G_M000_IG11                        ; no: ReadInt32, a plain virtual call
  mov      rdi, qword ptr [r13+0x30]          ; DataPointer
  mov      esi, dword ptr [rdi+4*rax]         ; the argument
  mov      rdi, 0x72D164428420
  cmp      qword ptr [rcx+0x18], rdi          ; is the function the lambda seen while profiling?
  jne      G_M000_IG12                        ; no: call it through the delegate
  inc      esi                                ; value + 1, the lambda inlined
  ...
  call     [VectorDataWriterBase:WriteValue[int](int,ulong):this]   ; the only call left
  inc      rax                                ; next row

The read of the argument is the fast path we saw in part 1, a comparison of StorageType and a load. The JIT also guessed the lambda from profile data and inlined it, so value + 1 is the inc esi, and the only call left is WriteValue<int>.

In the table below, job 2 is the commit just before this change. The reader and writer changes of the previous posts had already taken IntFunction from 13.61 to 7.87 ms, and with this change it takes 2.50 ms. A function of two int arguments went from 11.59 to 3.14 ms, and a function of a double from 8.14 to 2.59 ms. The function that takes a string gains less, from 23.88 to 19.03 ms. It also creates a .NET string for every value, 38 MB for a million rows, which this change doesn’t touch:

MethodJobMeanMedianRatio
IntFunction1-1.5.613.46 ms13.61 ms1.00
IntFunction2-0407f4c8.06 ms7.87 ms0.60
IntFunction3-ee223da2.58 ms2.50 ms0.19
TwoIntFunction1-1.5.620.69 ms20.79 ms1.00
TwoIntFunction2-0407f4c11.63 ms11.59 ms0.56
TwoIntFunction3-ee223da3.16 ms3.14 ms0.15
DoubleFunction1-1.5.613.17 ms13.01 ms1.00
DoubleFunction2-0407f4c8.24 ms8.14 ms0.63
DoubleFunction3-ee223da2.65 ms2.59 ms0.20
StringFunction1-1.5.631.93 ms32.26 ms1.00
StringFunction2-0407f4c23.80 ms23.88 ms0.75
StringFunction3-ee223da19.09 ms19.03 ms0.60

In this run, 1.5.6 also measured the SUM in SQL, which runs no function at all, about 7% slower than the other jobs did. So the ratios against 1.5.6 in this section are a little better than they should be, and the steps between the rows are the numbers to look at.

Nullable results

The functions that take or return an int? gained less from that change. NullableIntFunction adds one to an int? argument, and after the change it still took 11.66 ms, more than four times as long as the same function on an int. It also allocated 21 MB for a million rows. That’s the box from part 2, because the result went through WriteValue<int?>, whose type switch boxed every nullable value that wasn’t NULL. The fix from part 2, which writes a nullable value as the type under it, removes the box here too. NullableIntFunction went down to 7.32 ms, and IntToNullableFunction, which takes an int and returns an int?, from 10.89 to 6.29 ms:

MethodJobMeanMedianRatioAllocatedAlloc Ratio
NullableIntFunction1-1.5.621.25 ms21.24 ms1.0021,195.43 KB1.000
NullableIntFunction3-ee223da11.74 ms11.66 ms0.5521,199.22 KB1.000
NullableIntFunction4-40b625b7.32 ms7.32 ms0.34104.33 KB0.005
IntToNullableFunction1-1.5.619.51 ms19.50 ms1.0023,539.21 KB1.000
IntToNullableFunction3-ee223da10.96 ms10.89 ms0.5623,543.01 KB1.000
IntToNullableFunction4-40b625b6.30 ms6.29 ms0.32104.32 KB0.004

As you can see, that still left IntToNullableFunction more than twice as slow as IntFunction, although both add one to an int. The difference is how the result reaches the writer. On the commit just before the next fix, the loop looks like this:

; DuckDB.NET d9bf172, the loop of RegisterScalarFunction<int, int?>
  mov      esi, dword ptr [rdi+4*rax]         ; the argument
  ...
  inc      esi                                ; value + 1, the lambda inlined
  mov      byte  ptr [rbp-0x38], 1            ; the int? on the stack: HasValue
  mov      dword ptr [rbp-0x34], esi          ; and Value
  mov      rsi, qword ptr [rbp-0x38]          ; both read back as one 8-byte value
  ...
  call     [VectorDataWriterBase:WriteValue[System.Nullable`1[int]](System.Nullable`1[int],ulong):this]

The JIT inlines the lambda and builds its int? result on the stack with two stores, one byte for HasValue and four bytes for the value. Then it reads both back with one 8-byte load to pass the int? to WriteValue<int?>. The CPU can’t hand the data of two smaller stores that are still in flight to one larger load, so it waits for the stores to finish. Part 5 looks at that wait in detail. WriteValue<int?> then passes the value by reference to WriteNullable, which isn’t inlined.

The fix takes a nullable result apart in the loop and writes its value as the type under it:

// DuckDB.NET 1.5.6.1, the loop of RegisterScalarFunction<T, TResult>
for (ulong index = 0; index < rowCount; index++)
{
  var result = func(ReadValue<T>(reader, index, nullable, anyNullable));
  if (typeof(TResult).IsValueType && default(TResult) is null) WriteResult(writer, result, index); else writer.WriteValue(result, index);
}

// DuckDB.NET 1.5.6.1, DuckDBConnectionScalarFunctionExtensions
private static void WriteResult<TResult>(VectorDataWriterBase writer, TResult result, ulong index)
{
  if (typeof(TResult).IsValueType && default(TResult) is null)
  {
    ...
    if (typeof(TResult) == typeof(int?)) { WriteNullableResult(writer, (int?)(object?)result, index); return; }
    if (typeof(TResult) == typeof(long?)) { WriteNullableResult(writer, (long?)(object?)result, index); return; }
    ... // one line for every nullable type a function can return
  }

  writer.WriteValue(result, index);
}

private static void WriteNullableResult<TValue>(VectorDataWriterBase writer, TValue? value, ulong index) where TValue : struct
{
  if (value.HasValue)
  {
    writer.WriteValue(value.GetValueOrDefault(), index);
  }
  else
  {
    writer.WriteNull(index);
  }
}

The typeof checks are constants for the JIT, so only the int? line is left, and the cast through object? is removed too without boxing anything. In part 2 I used Unsafe.As for the same job, but here it would take the address of the result and bring the 8-byte load back. Now the value and HasValue stay in registers:

; DuckDB.NET 80216f9, the loop of RegisterScalarFunction<int, int?>
  mov      esi, dword ptr [rdi+4*rcx]         ; the argument
  ...
  inc      esi                                ; value + 1, the lambda inlined
  mov      r8d, 1                             ; HasValue, in a register
  test     r8d, r8d
  jne      G_M000_IG04                        ; it has a value
  ...                                         ; no value: WriteNull, inlined
G_M000_IG04:
  call     [VectorDataWriterBase:WriteValue[int](int,ulong):this]   ; written as an int

With the fix, IntToNullableFunction went from 6.27 to 2.50 ms, about the time of IntFunction, and NullableIntFunction from 7.33 to 4.02 ms:

MethodJobMeanMedianRatio
NullableIntFunction1-1.5.621.25 ms21.24 ms1.00
NullableIntFunction5-d9bf1727.36 ms7.33 ms0.35
NullableIntFunction6-80216f94.02 ms4.02 ms0.19
IntToNullableFunction1-1.5.619.51 ms19.50 ms1.00
IntToNullableFunction5-d9bf1726.27 ms6.27 ms0.32
IntToNullableFunction6-80216f92.54 ms2.50 ms0.13

Table functions

Rows that keep their type

Now that we have covered scalar functions, let’s look at table functions. A table function returns rows that a query reads like a table. With the simpler API from 1.5, you give DuckDB.NET the rows and a projection that turns a row into columns:

connection.RegisterTableFunction("bench_rows", () => rows, row => new { row.Id, row.Value, row.Ratio, row.Optional });

DuckDB asks for the rows one chunk at a time, through a callback. In DuckDB.NET 1.5.6 the callback held the rows as a non-generic IEnumerator and handed each row to a Mapper that took it as an object:

// DuckDB.NET 1.5.6, DuckDBConnection.TableFunction
private static void TableFunction(IntPtr info, IntPtr chunk)
{
  ...
  for (; size < DuckDBGlobalData.VectorSize; size++)
  {
    if (tableFunctionInitData.Enumerator.MoveNext())
    {
      tableFunctionInfo.Mapper(tableFunctionInitData.Enumerator.Current, writers, size);
    }
    else
    {
      break;
    }
  }
  ...
}

// DuckDB.NET 1.5.6, DuckDBConnectionTableFunctionExtensions.ParseProjection
void Mapper(object? item, IDuckDBDataWriter[] writers, ulong rowIndex)
{
  combinedWriter((TData)item!, writers, rowIndex);   // the compiled writer of the row
}

IEnumerator.Current returns an object, so a row that is a struct is boxed on every call, and Mapper unboxes it again for the compiled writer of the row. A row that is a class isn’t boxed, but it still goes through two interface calls and a delegate call. On the commit just before the fix, the loop of the callback looks like this (edited for brevity):

; DuckDB.NET dbb63cd, DuckDBConnection.TableFunction, one row
  call     [r11]System.Collections.IEnumerator:MoveNext():bool:this               ; an interface call
  ...
  call     [r11]System.Collections.IEnumerator:get_Current():System.Object:this   ; another one, the row as an object
  ...
  call     [rax+0x18]System.Action`3[__Canon,__Canon,ulong]:Invoke(...)           ; Mapper(object, writers, row)
  inc      rbx                                                                    ; next row

The struct rows of the benchmark have eight int properties. That’s 32 bytes, and with the object header the box is 48 bytes, so a million rows allocate 45.9 MB.

The fix adds a scan that knows the type of its rows. The callback that DuckDB calls is static and can’t be generic, so it calls Fill on the scan’s non-generic base class once for every chunk, and the generic class keeps the type of the rows from there to the writer. An array and a List<T> are read by position, and any other source is enumerated as IEnumerator<T>:

// DuckDB.NET 1.5.6.1, TableFunctionScan
internal abstract class TableFunctionScan : IDisposable
{
  public abstract ulong Fill(VectorDataWriterBase[] writers, ulong maxRows);

  public static TableFunctionScan Create<T>(IEnumerable<T> rows, Action<T, VectorDataWriterBase[], ulong> write) => rows switch
  {
    T[] array => new ArrayScan<T>(array, write),
    List<T> list when list.GetType() == typeof(List<T>) => new ListScan<T>(list, write),
    _ => new EnumeratorScan<T>(rows.GetEnumerator(), write)
  };

  private sealed class ArrayScan<T>(T[] rows, Action<T, VectorDataWriterBase[], ulong> write) : TableFunctionScan
  {
    private int position;

    public override ulong Fill(VectorDataWriterBase[] writers, ulong maxRows)
    {
      var count = (int)Math.Min(maxRows, (ulong)(rows.Length - position));
      var chunk = new ReadOnlySpan<T>(rows, position, count);

      for (var index = 0; index < chunk.Length; index++)
      {
        write(chunk[index], writers, (ulong)index);
      }

      position += count;
      return (ulong)count;
    }
  }
  ...
}

Fill of an array of structs is now a loop with one call for every row, and the call gets the struct itself:

; DuckDB.NET 909c0cf, TableFunctionScan.ArrayScan<StructRow>.Fill, one row
  mov      rsi, qword ptr [rdx+r13]           ; the row, read from the array by position
  mov      rdx, qword ptr [r13+rdx+0x08]
  ...
  call     [r9+0x18]System.Action`3[StructRow,__Canon,ulong]:Invoke(StructRow,...)   ; the writer of the row
  inc      eax                                ; next row

In the table below, job 4 is the commit just before this change, which has the changes of the previous posts and of the scalar function section. Struct rows with one column went from 13.69 to 3.80 ms, and their allocations from 45.9 MB to 40 KB. Class rows, which were never boxed, went from 7.87 to 4.12 ms with one column, and rows that come from an iterator from 7.92 to 5.44 ms. With eight columns the gain is smaller for every kind of row:

MethodJobColumnsMeanMedianRatioAllocatedAlloc Ratio
StructRows1-1.5.6117.21 ms17.14 ms1.0046,962.50 KB1.000
StructRows4-dbb63cd113.73 ms13.69 ms0.8046,962.48 KB1.000
StructRows5-909c0cf13.82 ms3.80 ms0.2240.17 KB0.001
StructRows1-1.5.6858.61 ms58.51 ms1.0047,286.61 KB1.000
StructRows4-dbb63cd829.98 ms29.85 ms0.5147,286.62 KB1.000
StructRows5-909c0cf820.21 ms20.07 ms0.34203.87 KB0.004
ClassRows1-1.5.6111.31 ms11.29 ms1.0086.01 KB1.00
ClassRows4-dbb63cd18.11 ms7.87 ms0.7285.99 KB1.00
ClassRows5-909c0cf14.13 ms4.12 ms0.3740.16 KB0.47
ClassRows1-1.5.6852.46 ms52.42 ms1.00410.18 KB1.00
ClassRows4-dbb63cd823.30 ms23.27 ms0.44410.14 KB1.00
ClassRows5-909c0cf820.31 ms20.29 ms0.39203.86 KB0.50
EnumeratedRows1-1.5.6110.93 ms10.90 ms1.0086.06 KB1.00
EnumeratedRows4-dbb63cd17.95 ms7.92 ms0.7386.03 KB1.00
EnumeratedRows5-909c0cf15.48 ms5.44 ms0.5040.23 KB0.47
EnumeratedRows1-1.5.6858.57 ms52.79 ms1.02410.25 KB1.00
EnumeratedRows4-dbb63cd824.24 ms24.22 ms0.42410.18 KB1.00
EnumeratedRows5-909c0cf821.68 ms21.60 ms0.38203.93 KB0.50

The times of 1.5.6 for eight columns of rows from an iterator vary a lot from one iteration to the next, so the median is the number to look at for that row.

Writing only the columns a query reads

Next, let’s look at the writer of a row. It is compiled from the projection with expression trees, and DuckDB.NET 1.5.6 compiled it once, when the function was registered, for every column:

// DuckDB.NET 1.5.6, DuckDBConnectionTableFunctionExtensions.CompileCombinedWriter
for (int i = 0; i < columnCount; i++)
{
  var reboundAccessor = replacer.Visit(accessors[i]);   // data.Id, data.Value, ...
  var writerAccess = Expression.ArrayIndex(writersParam, Expression.Constant(i));

  writeCalls[i] = Expression.Call(writerAccess, WriteValueMethod.MakeGenericMethod(types[i]), reboundAccessor, rowIndexParam);
}
// (data, writers, rowIndex) => { writers[0].WriteValue(data.Id, rowIndex); writers[1].WriteValue(data.Value, rowIndex); ... }

A column that the query doesn’t read gets a writer that does nothing, but its value is still read from the row and handed to that writer through the interface. The change from the scalar function section added a test for VectorDataWriterBase in front of every column, so a column that the query reads calls WriteValue<T> directly. That’s the code just before the fix, and for four columns it compiles to 470 bytes:

; DuckDB.NET 909c0cf, the compiled writer of a row, first column
  mov      r13, gword ptr [rbx+0x10]          ; writers[0]
  mov      rsi, r13
  mov      rdi, 0x702760180430                ; VectorDataWriterBase
  call     [CORINFO_HELP_ISINSTANCEOFCLASS]   ; is writers[0] a VectorDataWriterBase?
  test     rax, rax
  je       G_M000_IG11                        ; no, a column the query doesn't read
  mov      esi, dword ptr [rbp-0x30]          ; data.A
  call     [VectorDataWriterBase:WriteValue[int](int,ulong):this]
  ...                                         ; the same for the other three columns
G_M000_IG11:
  call     [CORINFO_HELP_VIRTUAL_FUNC_PTR]    ; look up WriteValue<int> of the writer that does nothing
  call     rax

So SELECT sum(Id) FROM bench_rows() makes four type tests for every row, and three lookups and calls for writers that do nothing.

My first attempt kept the writer compiled once and made the test for the writer that does nothing cheaper. A test of its type compiled to a call of Object.GetType and gained nothing. Comparing the writer with the one instance that does nothing was faster, but the writer still tested every column for every row and still read the values of the columns the query doesn’t need.

DuckDB tells a table function which columns a query reads when it starts a scan. DuckDB.NET 1.5.6.1 compiles the writer of a row then, for those columns only, and keeps it by the list of columns, so the same query run again finds it:

// DuckDB.NET 1.5.6.1, DuckDBConnectionTableFunctionExtensions
var writers = new ConcurrentDictionary<string, Action<TData, VectorDataWriterBase[], ulong>>();

return (columns, (data, projected, _) =>
{
  var writeRow = writers.GetOrAdd(string.Join(',', projected), _ => CompileRowWriter<TData>(projected, types, accessors, parameter));

  return TableFunctionScan.Create((IEnumerable<TData>)data, writeRow);
});

private static Action<TData, VectorDataWriterBase[], ulong> CompileRowWriter<TData>(int[] projected, Type[] types, Expression[] accessors, ParameterExpression originalParam)
{
  ...
  for (int i = 0; i < projected.Length; i++)
  {
    var column = projected[i];
    var reboundAccessor = replacer.Visit(accessors[column]);
    var writerAccess = Expression.ArrayIndex(writersParam, Expression.Constant(i));

    writeCalls[i] = Expression.Call(writerAccess, WriteValueMethod.MakeGenericMethod(types[column]), reboundAccessor, rowIndexParam);
  }
  ...
}

The value of a column that the query doesn’t read isn’t worked out at all any more. For one column, the compiled writer is now a bounds check and a jump to WriteValue<int>:

; DuckDB.NET ea7aefe, the compiled writer of a row, one column
  push     rax
  cmp      dword ptr [rcx+0x08], 0            ; bounds check of the writers
  jbe      SHORT G_M000_IG04
  mov      rdi, gword ptr [rcx+0x10]          ; writers[0]
  mov      rdx, r8                            ; the row
  cmp      dword ptr [rdi], edi               ; null check
  add      rsp, 8
  tail.jmp [VectorDataWriterBase:WriteValue[int](int,ulong):this]   ; data.A
G_M000_IG04:
  call     CORINFO_HELP_RNGCHKFAIL

For four columns it’s 141 bytes, three calls and a jump, with no type test. With this change, the query that reads one of four columns went from 14.83 to 3.14 ms:

MethodJobMeanMedianRatioAllocatedAlloc Ratio
TableFunctionOneColumn1-1.5.619.68 ms19.49 ms1.0097.38 KB1.00
TableFunctionOneColumn5-909c0cf14.86 ms14.83 ms0.7640.05 KB0.41
TableFunctionOneColumn6-ea7aefe3.17 ms3.14 ms0.1640.07 KB0.41

Queries that read every column gain too, without the type tests. Struct rows with one column went from 3.80 to 2.65 ms, and eight columns of class rows from 20.29 to 14.83 ms:

MethodJobColumnsMeanMedianRatio
StructRows1-1.5.6117.21 ms17.14 ms1.00
StructRows5-909c0cf13.82 ms3.80 ms0.22
StructRows6-ea7aefe12.65 ms2.65 ms0.15
ClassRows1-1.5.6852.46 ms52.42 ms1.00
ClassRows5-909c0cf820.31 ms20.29 ms0.39
ClassRows6-ea7aefe814.86 ms14.83 ms0.28
StructRows1-1.5.6858.61 ms58.51 ms1.00
StructRows5-909c0cf820.21 ms20.07 ms0.34
StructRows6-ea7aefe814.61 ms14.56 ms0.25

All the table function changes together

The table function of the results table has four columns, one of them an int?, and every change in this post touches it. The changes of the previous posts took it from 37.94 to 29.10 ms, and the loop without generic virtual calls to 23.04 ms. The commit before the typed scan also has the nullable write from part 2, which removed the 20.8 MB of boxes of the int? column. The typed scan and the writer for the columns a query reads took it the rest of the way, and in 1.5.6.1 it takes 9.79 ms, about 3.9 times as fast as in 1.5.6:

MethodJobMeanMedianRatioAllocatedAlloc Ratio
TableFunction1-1.5.638.41 ms37.94 ms1.0021,334.82 KB1.000
TableFunction2-0407f4c29.24 ms29.10 ms0.7621,334.80 KB1.000
TableFunction3-ee223da23.02 ms23.04 ms0.6021,334.80 KB1.000
TableFunction4-dbb63cd17.27 ms17.26 ms0.45239.71 KB0.011
TableFunction5-909c0cf14.06 ms14.10 ms0.37109.82 KB0.005
TableFunction6-ea7aefe10.27 ms10.41 ms0.27109.92 KB0.005
TableFunction7-1.5.6.19.78 ms9.79 ms0.25109.92 KB0.005

Reading the same kind of rows from a table instead of a table function took the same time in every job, 0.37 to 0.38 ms for one column, so all of the time saved is in DuckDB.NET.

Reading lists, structs and maps

Working out the target type once per column

Finally, let’s see how DuckDB.NET reads lists, structs and maps. GetFieldValue<List<int>> reads a LIST or ARRAY column as a List<int>, GetFieldValue<T> with a class reads a STRUCT into the properties of that class, and GetFieldValue<Dictionary<int, string>> reads a MAP. In DuckDB.NET 1.5.6, the list reader worked out what to do with the type you asked for on every row:

// DuckDB.NET 1.5.6, ListVectorDataReader
private object GetList(Type returnType, ulong listOffset, ulong length)
{
  if (!returnType.IsGenericType) { throw ... }

  var listType = returnType.GetGenericArguments()[0];   // allocates an array
  ...
  var allowNulls = listType.AllowsNullValue(out _, out var nullableType);

  var list = Activator.CreateInstance(returnType) as IList ?? throw ...;

  //Special case for specific types to avoid boxing
  return list switch
  {
    List<int> theList => BuildList(theList),
    List<int?> theList => BuildList(theList),
    ...   // float, double, decimal and their nullable forms
    _ => BuildListCommon(list, nullableType ?? listType)
  };
  ...
}

For every row it asked the type for its generic arguments, which allocates an array, checked whether the items can be NULL, created the list with Activator.CreateInstance and tested it against eight list types. The list also started empty and grew as the items were added. The struct reader did even more for every row. It created the object with Activator and looked its type up in a cache with a lambda that captured a parameter of the method, so every row allocated a closure. Then it looked up the reader of every field by name and set each property with a value passed as an object.

DuckDB.NET 1.5.6.1 keeps a plan for the type the reader was asked for last, because a column is read as the same type row after row:

// DuckDB.NET 1.5.6.1, ListVectorDataReader
private Type? planType;
private ListPlan plan;

private object GetList(Type returnType, ulong listOffset, ulong length)
{
  if (returnType != planType)
  {
    plan = CreatePlan(returnType);   // GetGenericArguments, AllowsNullValue and the type tests
    planType = returnType;
  }

  // The eight types read without boxing an item. The list is created with room for every item.
  var capacity = (int)length;

  return plan.Kind switch
  {
    ListKind.Int32 => BuildList(new List<int>(capacity), listOffset, length),
    ListKind.NullableInt32 => BuildNullableList(new List<int?>(capacity), listOffset, length),
    ...
    _ => BuildOtherList(returnType, listOffset, length)
  };
}

The struct reader pairs each property with the reader of its field once, in the same way. The allocations show what was saved for a list. A List<int> of five items now allocates 80 bytes per row, the list and its array of five items. In 1.5.6 it allocated 160 bytes, and the other 80 were the array from GetGenericArguments and the arrays the list grew through, with room for four items and then eight.

The reader changes of the previous posts are already in job 2, the commit just before this change. With the change, reading a List<int> went from 17.74 to 4.74 ms, a List<int?> with NULLs from 28.78 to 6.26 ms, and a MAP read as a Dictionary<int, string> from 22.46 to 10.17 ms:

MethodJobMeanMedianRatioAllocatedAlloc Ratio
ReadArrayAsListOfInt1-1.5.620.89 ms20.76 ms1.0030.52 MB1.00
ReadArrayAsListOfInt2-cedc17617.76 ms17.74 ms0.8530.52 MB1.00
ReadArrayAsListOfInt3-d9bf1724.76 ms4.74 ms0.2315.26 MB0.50
ReadListWithNullsAsListOfNullableInt1-1.5.632.74 ms32.44 ms1.0045.78 MB1.00
ReadListWithNullsAsListOfNullableInt2-cedc17628.76 ms28.78 ms0.8845.78 MB1.00
ReadListWithNullsAsListOfNullableInt3-d9bf1726.28 ms6.26 ms0.1918.32 MB0.40
ReadArrayAsListOfLong1-1.5.637.53 ms37.76 ms1.0085.46 MB1.00
ReadArrayAsListOfLong2-cedc17631.72 ms31.59 ms0.8585.46 MB1.00
ReadArrayAsListOfLong3-d9bf17221.93 ms21.75 ms0.5879.35 MB0.93
ReadStructAsClass1-1.5.616.61 ms16.64 ms1.0028.23 MB1.00
ReadStructAsClass2-cedc17614.78 ms14.78 ms0.8928.23 MB1.00
ReadStructAsClass3-d9bf1729.31 ms9.27 ms0.5623.66 MB0.84
ReadStructAsDictionary1-1.5.616.57 ms16.57 ms1.0061.80 MB1.00
ReadStructAsDictionary2-cedc17616.05 ms15.98 ms0.9761.81 MB1.00
ReadStructAsDictionary3-d9bf17215.20 ms15.29 ms0.9257.23 MB0.93
ReadMapAsDictionary1-1.5.622.97 ms23.00 ms1.0060.28 MB1.00
ReadMapAsDictionary2-cedc17622.51 ms22.46 ms0.9860.28 MB1.00
ReadMapAsDictionary3-d9bf17210.32 ms10.17 ms0.4552.65 MB0.87

As you can see, the other three reads changed much less. A List<long> read from an INTEGER column went from 31.59 to 21.75 ms, a STRUCT read into a class from 14.78 to 9.27 ms, and a STRUCT read as a Dictionary<string, object> only from 15.98 to 15.29 ms. Every item of a list whose type differs from the type stored, every field of a struct and every key and value of a map is still read as an object and boxed, and such a list is still created with Activator and grows as items are added. Reading them the typed way changes what some reads return, so I left that for DuckDB.NET 2.0.

What’s next

The last post of the series explains the wait that showed up four times and how to find such problems yourself. We saw it in List<int?> in part 2, in the wide decimal read and the decimal append in part 3, and in the nullable function result in this post. 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.