ADO.NET: ClickHouseParameterCollection name lookups are linear, so Dapper parameter binding is O(n²)

Open
#698 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

@XSY-28 is already working on this.

Since Nov 25, 2026.

  • #773 by @XSY-28 — open

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
46/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
csharp

Research direction

Start with ClickHouse.Driver/ADO/Parameters/ClickHouseParameterCollection.cs and inspect Contains, IndexOf, the name indexer, and RemoveAt(string); use the Dapper 2.1.86 AddParameters call and the supplied benchmark as the entry points. Preserve ordinal case-sensitive lookup, first-match IndexOf, removal of all duplicate names, null-name behavior, and correct results when ParameterName changes after insertion. Done means lookups remain correct across collection mutations and renames while parameter binding scales approximately linearly.

Written by the indexing model from the issue text.

Description

bug queries
Describe the bug

ClickHouseParameterCollection.Contains(string) and IndexOf(string) scan the full parameter list. Dapper calls command.Parameters.Contains(name) one time for each parameter that it binds, so binding n parameters through Dapper costs O(n²) name comparisons. This is client-side CPU time, spent before the request is built.

Scope:

  • With default server settings, one request carries about 1,000 parameters at most: http_max_fields defaults to 1000, and above it the server returns HTML Form Exception: Too many form fields. At 1,000 parameters the extra cost is about 6 ms, so a default setup does not see it.
  • The cost shows when the user profile raises http_max_fields, the same large-command scenario as #696. When #696 is fixed (#697), this becomes the largest client-side cost for Dapper users. Binding costs 1.2 s at 18,000 parameters (the same as the #696 rewrite before its fix) and 40 s at 72,000 (the unfixed #696 rewrite: 9.4 s).
  • For a multi-row parameterized INSERT ... VALUES, the server's own time is larger still: query_duration_ms was 8.8 s at 9,000 parameters and 45.6 s at 18,000. For a large IN (...) list, the client side is the larger part (second table below).
Steps to reproduce
  1. Add n parameters with the pattern that Dapper uses: check Contains(name), then Add.
  2. Compare with the same parameters added through Parameters.Add only.
  3. Double n and look at the time.
Code example

No server is necessary for this part:

var coll = new ClickHouseParameterCollection();
var sw = Stopwatch.StartNew();
for (var i = 0; i < n; i++)
{
    var name = "p" + i;
    if (!coll.Contains(name)) // Dapper does this for each parameter
        coll.Add(new ClickHouseDbParameter { ParameterName = name, Value = i });
}
Console.WriteLine($"{n}: {sw.Elapsed.TotalMilliseconds:F1} ms");

The same cost on the real Dapper path:

var dict = Enumerable.Range(0, n).ToDictionary(i => "p" + i, i => (object)i);
var sql = $"SELECT count() FROM numbers(10000000) WHERE number IN ({string.Join(",", dict.Keys.Select(k => "@" + k))})";
await connection.ExecuteScalarAsync<long>(sql, new DynamicParameters(dict));   // Dapper
// compare: ClickHouseCommand with the same CommandText, cmd.Parameters.Add(...) for each entry, ExecuteScalarAsync()

Binding only, no server round trip (net10.0 Release, best of 3). The first column calls Dapper's SqlMapper.IDynamicParameters.AddParameters(cmd, identity) on a ClickHouseCommand directly:

Parameters Dapper AddParameters Same parameters, Parameters.Add only Contains-then-Add loop above
1,000 6.3 ms 0.2 ms 7.2 ms
4,000 45.7 ms 0.3 ms 52.8 ms
8,000 275 ms 0.3 ms 331 ms
18,000 1,215 ms 0.7 ms 1,280 ms
36,000 4,820 ms 2.9 ms 6,511 ms
72,000 40,120 ms 3.3 ms 39,348 ms

End to end, the IN (...) query above, against a live server with a raised http_max_fields (median of 5):

Parameters Dapper ExecuteScalarAsync ClickHouseCommand + Parameters.Add Difference
1,000 174 ms 139 ms 35 ms
4,000 670 ms 579 ms 92 ms
9,000 2,556 ms 2,159 ms 397 ms

At 1,000 parameters, most of the difference is Dapper's own per-parameter work: the Contains part is about 6 ms. Server-side query_duration_ms was about 105 / 350 / 740 ms for the three rows. Above about 16,000 list elements, this query fails with TOO_BIG_AST at the default max_ast_elements.

Expected behaviour

A name lookup does not depend on the parameter count. Then binding n parameters through an ORM costs O(n), like adding them with Parameters.Add (3.3 ms for 72,000 parameters).

Root cause

In ClickHouse.Driver/ADO/Parameters/ClickHouseParameterCollection.cs, the name lookups are list scans:

  • line 30: Contains(string value) => parameters.Any(p => p.ParameterName == value)
  • line 44: IndexOf(string parameterName) => parameters.FindIndex(x => x.ParameterName == parameterName)
  • this[string] get (line 56) and set (line 60) go through IndexOf. RemoveAt(string) (line 52) is also a full scan.

Dapper (the version that this repo pins) calls Contains one time for each parameter in DynamicParameters.AddParameters, DynamicParameters.cs line 253:

bool add = !command.Parameters.Contains(name);

The template path (new DynamicParameters(new { ... }), AddDynamicParams(obj)) goes through SqlMapper.FindOrAddParameter, which calls Contains(name) and then the name indexer. The driver itself never calls these name lookups, so only external callers such as ORMs pay the cost.

The fix is a name index in ClickHouseParameterCollection.

Polyglot AI can open a fix PR if a maintainer assigns this issue to @polyglotAI-bot.

Configuration
Environment
  • Client version: main @ c8a72abf (after 1.5.0)
  • Language version: C#, built for net10.0
  • .NET version: 10.0.13 runtime
  • Dapper: 2.1.86
  • OS: Linux (Docker, 4 cores)
ClickHouse server
  • ClickHouse Server version: 26.9.1.1629
  • ClickHouse Server non-default settings, if any: http_max_fields = 1000000 in the default profile, for the end-to-end numbers only. The binding-only numbers do not use a server.
  • CREATE TABLE statements for tables involved: none (numbers())

Classification: impact: Performance · area: Queries (parameter binding)


Found by automated analysis (Polyglot AI) while working on #696. Verified against a live server.

Dominant language
C#
Stars
102
Forks
31
Avg merge
2d 13h
Merged PRs (30d)
40

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from ClickHouse/clickhouse-cs

All issues in ClickHouse/clickhouse-cs

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.