Skip to content

Avoid resolving column serializers for every row in RowBinaryFormatWriter #3492

Backlog

Description

@Harry262530

RowBinaryFormatWriter performs serializer resolution for each column during row commit. This means the serializer for a column may be resolved repeatedly for every row, even though the writer’s schema does not change.

For R rows and C columns, this introduces approximately R × C serializer-resolution operations in the serialization hot path.

This issue is a subpart of the issue #3289

Activity

  1. polyglotAI-bot commented on Dec 2, 2026

    @polyglotAI-bot
    Collaborator

    Recommendation: Keep open — maintainer decision
    This issue splits points 3 and 4 of #3289 into their own issue, and #3289 still has no answer to the contributor's offer of a PR. Decide whether to accept a PR for this part and make it a sub-issue of #3289, or close it as a duplicate of #3289.

    • Category: Performance
    • Classification: impact: Performance · area: Data types & formats (RowBinary)
    • Status on main: Reproduced on main — the per-cell calls of commitRow take about 50 ns for each row of 20 Int64 columns (2.5 ns per cell), 25–30 % of the writer's time. They allocate nothing.
    • Breaking change: No — can be done without a break. The class is marked "Experimental API".
    • Duplicates / related: No others

    Analysis: For each cell, commitRow reads the column and its default (client-v2/src/main/java/com/clickhouse/client/api/data_formats/RowBinaryFormatWriter.java:91-96), writeValuePreamble reads the nullability, type, and default again (RowBinaryFormatSerializer.java:195-196), and serializeData and serializePrimitiveData select the write with two switches on the type (internal/SerializerUtils.java:68, :656). The schema does not change during the life of the writer, so each row gets the same results.

    Reproduction: complete program and output
    import com.clickhouse.client.api.Client;
    import com.clickhouse.client.api.data_formats.RowBinaryFormatSerializer;
    import com.clickhouse.client.api.data_formats.RowBinaryFormatWriter;
    import com.clickhouse.client.api.data_formats.internal.SerializerUtils;
    import com.clickhouse.client.api.metadata.TableSchema;
    import com.clickhouse.data.ClickHouseColumn;
    import com.clickhouse.data.ClickHouseFormat;
    import com.clickhouse.data.format.BinaryStreamUtils;
    
    import java.io.IOException;
    import java.io.OutputStream;
    import java.lang.management.ManagementFactory;
    import java.util.List;
    
    public class Repro {
        static final String URL = System.getenv().getOrDefault("CLICKHOUSE_URL", "http://localhost:8123");
        static final String PASSWORD = System.getenv().getOrDefault("CLICKHOUSE_PASSWORD", "");
        static final int ROWS = 1_000_000;
        static final int COLS = 20;
        // Values boxed in advance, so that no case measures the boxing of the setters (#3289).
        static final Object[] VALUES = new Object[1024];
    
        /** Discards the bytes, so that only the serialization is measured. */
        static final class NullOut extends OutputStream {
            long n;
            @Override public void write(int b) { n++; }
            @Override public void write(byte[] b, int off, int len) { n += len; }
        }
    
        interface Body { void run(OutputStream out) throws IOException; }
    
        public static void main(String[] args) throws Exception {
            for (int i = 0; i < VALUES.length; i++) VALUES[i] = Long.valueOf(1_000_000L + i);
            TableSchema schema;
            try (Client client = new Client.Builder().addEndpoint(URL)
                    .setUsername("default").setPassword(PASSWORD).build()) {
                StringBuilder ddl = new StringBuilder("CREATE TABLE triage_3492 (");
                for (int c = 0; c < COLS; c++) ddl.append(c == 0 ? "" : ", ").append("c").append(c).append(" Int64");
                client.execute("DROP TABLE IF EXISTS triage_3492").get().close();
                client.execute(ddl.append(") ENGINE = Memory").toString()).get().close();
                schema = client.getTableSchema("triage_3492");
                client.execute("DROP TABLE triage_3492").get().close();
            }
            final TableSchema ts = schema;
            final List<ClickHouseColumn> cols = ts.getColumns();
    
            // 1. The writer: setValue stages the row, commitRow resolves the serializer of each cell.
            Body writer = out -> {
                RowBinaryFormatWriter w = new RowBinaryFormatWriter(out, ts, ClickHouseFormat.RowBinary);
                for (int r = 0; r < ROWS; r++) {
                    for (int c = 1; c <= COLS; c++) w.setValue(c, VALUES[(r + c) & 1023]);
                    w.commitRow();
                }
            };
            // 2. The calls that commitRow makes for each cell (RowBinaryFormatWriter.java:91-99), with no staging.
            Body perCell = out -> {
                for (int r = 0; r < ROWS; r++) {
                    for (int i = 0; i < COLS; i++) {
                        Object v = VALUES[(r + i + 1) & 1023];
                        ClickHouseColumn column = cols.get(i);
                        if (column.hasDefault() && column.getDefaultValue() != ClickHouseColumn.DefaultValue.DEFAULT) continue;
                        if (RowBinaryFormatSerializer.writeValuePreamble(out, false, column, v)) {
                            SerializerUtils.serializeData(out, v, column);
                        }
                    }
                }
            };
            // 3. Contrast: the same writes with the serializer known in advance (all columns are Int64).
            Body known = out -> {
                for (int r = 0; r < ROWS; r++)
                    for (int i = 0; i < COLS; i++) BinaryStreamUtils.writeInt64(out, (Long) VALUES[(r + i + 1) & 1023]);
            };
            Body[] bodies = {writer, perCell, known};
            String[] labels = {"RowBinaryFormatWriter setValue + commitRow",
                    "commitRow per-cell calls, no staging",
                    "BinaryStreamUtils.writeInt64, serializer known"};
            for (int i = 0; i < 3; i++) for (Body b : bodies) measure(null, b); // warm-up (JIT)
            for (int i = 0; i < bodies.length; i++) measure(labels[i], bodies[i]);
        }
    
        static void measure(String label, Body body) throws IOException {
            com.sun.management.ThreadMXBean mx = (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
            long tid = Thread.currentThread().getId();
            NullOut out = new NullOut();
            long a0 = mx.getThreadAllocatedBytes(tid);
            long t0 = System.nanoTime();
            body.run(out);
            long t1 = System.nanoTime();
            long a1 = mx.getThreadAllocatedBytes(tid);
            if (label != null) {
                System.out.printf("%s: %d rows x %d Int64, %d bytes, %.1f ns/row, %.1f B allocated/row%n",
                        label, ROWS, COLS, out.n, (t1 - t0) / (double) ROWS, (a1 - a0) / (double) ROWS);
            }
        }
    }

    Output on main (27d63e941), ClickHouse 26.11.7.10, OpenJDK 17.0.21.1 (in three runs, the writer case gave 170–200 ns/row, the other cases changed by less than 1 %):

    RowBinaryFormatWriter setValue + commitRow: 1000000 rows x 20 Int64, 160000000 bytes, 170.5 ns/row, 480.0 B allocated/row
    commitRow per-cell calls, no staging: 1000000 rows x 20 Int64, 160000000 bytes, 134.4 ns/row, 480.0 B allocated/row
    BinaryStreamUtils.writeInt64, serializer known: 1000000 rows x 20 Int64, 160000000 bytes, 84.4 ns/row, 480.0 B allocated/row
    

    Automated triage by Polyglot AI. A maintainer makes the final decision.

  2. added
    client
    data-types
    on Dec 2, 2026
  3. Harry262530 commented on Dec 2, 2026

    @Harry262530
    Author

    We will be raising a merge request in a while for this issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    clientdata-typesperformance

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions