Skip to content

[performance][jdbc] Reduce memory allocation in PreparedStatement #3333

Open

Description

@chernser

Description

Reduce allocations in JDBC when using PreparedStatement.

Activity

  1. added this to the 0.12.0 milestone on Nov 11, 2026
  2. added theissue type on Nov 11, 2026
  3. added
    jdbc
    planned_work
    on Nov 11, 2026
  4. polyglotAI-bot commented on Nov 27, 2026

    @polyglotAI-bot
    Collaborator

    Recommendation: Keep open — implementation needed
    Planned work of epic #3324. The run gives a baseline on main: prepareStatement (about 56 KB for each call), setTimestamp, and addBatch allocate the most.

    Analysis: Each set* call converts its value to SQL text at once (encodeObject, PreparedStatementImpl.java:764-862); setTimestamp goes through a ZonedDateTime and an Instant to a fromUnixTimestamp64Nano(...) string (PreparedStatementImpl.java:498-501, 786-789). addBatch copies the VALUES template and the values into a new StringBuilder for each row (PreparedStatementImpl.java:322-330). prepareStatement parses the SQL on each call, and nothing caches the result (ConnectionImpl.java:458).

    Reproduction: complete program and output

    Allocations of the calling thread (ThreadMXBean), after a warm-up run of the same calls.

    import java.lang.management.ManagementFactory;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.Timestamp;
    import java.util.Properties;
    
    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 com.sun.management.ThreadMXBean MX =
                (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
        static final String INSERT = "INSERT INTO t3333 (id, name, ts, v) VALUES (?, ?, ?, ?)";
        static final String NAME = "name-0123456789";
        static final Timestamp TS = Timestamp.valueOf("2026-11-27 10:20:30.123");
        static final int N = 100_000;
    
        interface Op { void run(PreparedStatement ps, int i) throws Exception; }
    
        static long allocated() {
            return MX.getThreadAllocatedBytes(Thread.currentThread().getId());
        }
    
        static void setRow(PreparedStatement ps, int i) throws Exception {
            ps.setLong(1, i);
            ps.setString(2, NAME);
            ps.setTimestamp(3, TS);
            ps.setDouble(4, 1.5);
        }
    
        // bytes allocated by one call of op, after a warm-up run of the same N calls
        static void perCall(Connection conn, String name, Op op) throws Exception {
            try (PreparedStatement ps = conn.prepareStatement(INSERT)) {
                setRow(ps, 0);
                for (int i = 0; i < N; i++) op.run(ps, i);
                ps.clearBatch();
                long before = allocated();
                for (int i = 0; i < N; i++) op.run(ps, i);
                System.out.printf("%-40s %6d B/call%n", name, (allocated() - before) / N);
            }
        }
    
        static void batch(Connection conn, String name) throws Exception {
            try (PreparedStatement ps = conn.prepareStatement(INSERT)) {
                for (int round = 0; round < 2; round++) { // round 0 is the warm-up
                    long before = allocated();
                    for (int i = 0; i < N; i++) {
                        setRow(ps, i);
                        ps.addBatch();
                    }
                    long filled = allocated();
                    ps.executeBatch();
                    long done = allocated();
                    if (round == 1) {
                        System.out.printf("%-40s %6d B/row set+addBatch, %6d B/row executeBatch%n",
                                name + " (" + ps.getClass().getSimpleName() + ")",
                                (filled - before) / N, (done - filled) / N);
                    }
                }
            }
        }
    
        static Connection connect(String extra) throws Exception {
            Properties props = new Properties();
            props.setProperty("user", "default");
            props.setProperty("password", PASSWORD);
            String jdbcUrl = "jdbc:clickhouse:" + URL.replaceFirst("^https?:", "") + "/default" + extra;
            return DriverManager.getConnection(jdbcUrl, props);
        }
    
        public static void main(String[] args) throws Exception {
            try (Connection conn = connect("")) {
                conn.createStatement().execute("DROP TABLE IF EXISTS t3333");
                conn.createStatement().execute(
                        "CREATE TABLE t3333 (id Int64, name String, ts DateTime64(3), v Float64) ENGINE = Memory");
    
                // prepareStatement parses the SQL for each call
                for (int round = 0; round < 2; round++) {
                    long before = allocated();
                    for (int i = 0; i < 10_000; i++) conn.prepareStatement(INSERT).close();
                    if (round == 1) System.out.printf("%-40s %6d B/call%n", "prepareStatement (INSERT, 4 ?)", (allocated() - before) / 10_000);
                }
                perCall(conn, "setLong", (ps, i) -> ps.setLong(1, i));
                perCall(conn, "setString (15 chars)", (ps, i) -> ps.setString(2, NAME));
                perCall(conn, "setTimestamp", (ps, i) -> ps.setTimestamp(3, TS));
                perCall(conn, "setDouble", (ps, i) -> ps.setDouble(4, 1.5));
                perCall(conn, "addBatch (4 values set)", (ps, i) -> ps.addBatch());
                batch(conn, "batch of " + N + " rows, default");
            }
            // contrast: the RowBinary writer of jdbc-v2 (beta option)
            try (Connection conn = connect("?beta.row_binary_for_simple_insert=true")) {
                batch(conn, "batch of " + N + " rows, RowBinary writer");
                conn.createStatement().execute("DROP TABLE t3333");
            }
        }
    }

    Output on main (8480ca001), ClickHouse 26.11.2.4:

    prepareStatement (INSERT, 4 ?)            55720 B/call
    setLong                                      71 B/call
    setString (15 chars)                        176 B/call
    setTimestamp                                472 B/call
    setDouble                                    72 B/call
    addBatch (4 values set)                     320 B/call
    batch of 100000 rows, default (PreparedStatementImpl)   1055 B/row set+addBatch,    475 B/row executeBatch
    batch of 100000 rows, RowBinary writer (WriterStatementImpl)    459 B/row set+addBatch,     44 B/row executeBatch
    

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

  5. added
    queries
    on Nov 27, 2026
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

    jdbcperformanceplanned_workqueries

    Type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions