pg.ddx.io  pgsql-jdbc@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Mikko Tiihonen <mikko.tiihonen@iki.fi>
To: pgsql-jdbc@postgresql.org
Subject: ResultSet.getBytes() of bytea speedup batch
Date: Fri, 17 Nov 2006 00:20:29 +0200
Message-ID: <1163715629.8932.22.camel@mokki.local> (raw)

Hi,

I spent two lonely nights trying to optimise the retrieving of binary
data from bytea column when using ResultSet.getBytes().

The attached patch gives 20-400% speedup depending on the bytea column
size. The speedup comes from switching to the binary transfer mode
instead of the text transfer mode for bytea columns.

The patch also contains the test code which I used to test the
performance (ByteaBenchTest.java). The benchmark results are:

cvs:
column size:    transfer speed:
    512b speed:   3,8MB/s
   2048b speed:  10,0MB/s
   4096b speed:  13,1MB/s
  16384b speed:  22,0MB/s
  65536b speed:  22,4MB/s
1048576b speed:  21,2MB/s

patch:
column size:    transfer speed:
    512b speed:   4,6MB/s -  21% speedup
   2048b speed:  16,8MB/s -  68% speedup
   4096b speed:  27,9MB/s - 112% speedup
  16384b speed:  79,2MB/s - 260% speedup
  65536b speed: 111,1MB/s - 395% speedup (optimal for my L2 cache?)
1048576b speed:  74,8MB/s - 252% speedup

The benchmark was run on Java6rc build 104 with postgresql 8.1.5 running
on localhost with Athlon64 2x2GHz, 64bit mode.

---

What the patch does:

After executing a prepared statement the first time the result set field
information (Field[]) is cached into the prepared query object.
Subsequent executions of the prepared statements use the field
types to decide when to request binary encoding from the server.
Currently only bytea types request binary encoding. The caching seems
safe because the Field objects are immutable.

Still open questions:
- is there any better way to obtain the result set field information in
QueryExecutor?
  * could the result set type information be obtained during the
prepare?
- in which conditions should a prepared statement drop the cached fields
  * do the result set fields ever change?
  * any other conditions?
- if caching of Field information is allowed (at least in some
circumstances), could the driver stop requesting a Describe from the
backend?

-Mikko

Attachments:

getBinary-speedup.patch (text/x-patch, 11.9K) download diff -urN --exclude=CVS --exclude='*.class' --exclude='*.jar' pgjdbc.clean/org/postgresql/core/Query.java pgjdbc/org/postgresql/core/Query.java --- pgjdbc.clean/org/postgresql/core/Query.java 2005-01-11 10:25:43.000000000 +0200 +++ pgjdbc/org/postgresql/core/Query.java 2006-11-17 00:18:01.000000000 +0200 @@ -54,4 +54,20 @@ * A closed Query should not be executed. */ void close(); + + /** + * Sets the fields that this query will return. + * + * @param fields The fields that this query will return. + */ + void setFields(Field[] fields); + + /** + * Returns the fields that this query will return. If the result set fields + * are not known returns null. + * + * @return the fields that this query will return. + */ + Field[] getFields(); + } diff -urN --exclude=CVS --exclude='*.class' --exclude='*.jar' pgjdbc.clean/org/postgresql/core/v2/V2Query.java pgjdbc/org/postgresql/core/v2/V2Query.java --- pgjdbc.clean/org/postgresql/core/v2/V2Query.java 2006-11-02 17:31:14.000000000 +0200 +++ pgjdbc/org/postgresql/core/v2/V2Query.java 2006-11-17 00:23:42.000000000 +0200 @@ -95,6 +95,13 @@ public void close() { } + public Field[] getFields() { + return null; + } + + public void setFields(Field[] fields) { + } + String[] getFragments() { return fragments; } diff -urN --exclude=CVS --exclude='*.class' --exclude='*.jar' pgjdbc.clean/org/postgresql/core/v3/CompositeQuery.java pgjdbc/org/postgresql/core/v3/CompositeQuery.java --- pgjdbc.clean/org/postgresql/core/v3/CompositeQuery.java 2005-01-11 10:25:44.000000000 +0200 +++ pgjdbc/org/postgresql/core/v3/CompositeQuery.java 2006-11-17 00:18:01.000000000 +0200 @@ -56,6 +56,13 @@ return subqueries; } + public Field[] getFields() { + return null; + } + + public void setFields(Field[] fields) { + } + private final SimpleQuery[] subqueries; private final int[] offsets; } diff -urN --exclude=CVS --exclude='*.class' --exclude='*.jar' pgjdbc.clean/org/postgresql/core/v3/QueryExecutorImpl.java pgjdbc/org/postgresql/core/v3/QueryExecutorImpl.java --- pgjdbc.clean/org/postgresql/core/v3/QueryExecutorImpl.java 2006-11-02 17:31:14.000000000 +0200 +++ pgjdbc/org/postgresql/core/v3/QueryExecutorImpl.java 2006-11-17 00:45:16.000000000 +0200 @@ -805,12 +805,22 @@ encodedSize += (long)4 + params.getV3Length(i); } + int binaryResults = 0; + Field[] fields = query.getFields(); + if (fields != null) { + for (int i = 0; i < fields.length; ++i) { + if (useBinary(fields[i])) { + binaryResults = i + 1; + } + } + } + encodedSize = 4 + (encodedPortalName == null ? 0 : encodedPortalName.length) + 1 + (encodedStatementName == null ? 0 : encodedStatementName.length) + 1 + 2 + params.getParameterCount() * 2 + 2 + encodedSize - + 2; + + 2 + binaryResults * 2; // backend's MaxAllocSize is the largest message that can // be received from a client. If we have a bigger value @@ -865,7 +875,11 @@ } } - pgStream.SendInteger2(0); // # of result format codes (0) + pgStream.SendInteger2(binaryResults); // # of result format codes + for (int i = 0; i < binaryResults; ++i) { + pgStream.SendInteger2(useBinary(fields[i]) ? Field.BINARY_FORMAT : + Field.TEXT_FORMAT); + } pendingBindQueue.add(portal); @@ -874,6 +888,10 @@ throw bindException; } } + + private boolean useBinary(Field field) { + return field.getOID() == Oid.BYTEA; + } private void sendDescribePortal(Portal portal) throws IOException { // diff -urN --exclude=CVS --exclude='*.class' --exclude='*.jar' pgjdbc.clean/org/postgresql/core/v3/SimpleQuery.java pgjdbc/org/postgresql/core/v3/SimpleQuery.java --- pgjdbc.clean/org/postgresql/core/v3/SimpleQuery.java 2006-08-06 21:02:45.000000000 +0300 +++ pgjdbc/org/postgresql/core/v3/SimpleQuery.java 2006-11-17 00:19:58.000000000 +0200 @@ -54,6 +54,14 @@ unprepare(); } + public Field[] getFields() { + return fields; + } + + public void setFields(Field[] fields) { + this.fields = fields; + } + // // V3Query // @@ -126,6 +134,8 @@ private byte[] encodedStatementName; private PhantomReference cleanupRef; private int[] preparedTypes; + private static final byte[] EMPTY_STATEMENTNAME = new byte[] { 0 }; + private Field[] fields; final static SimpleParameterList NO_PARAMETERS = new SimpleParameterList(0); } diff -urN --exclude=CVS --exclude='*.class' --exclude='*.jar' pgjdbc.clean/org/postgresql/jdbc2/AbstractJdbc2Statement.java pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Statement.java --- pgjdbc.clean/org/postgresql/jdbc2/AbstractJdbc2Statement.java 2006-11-05 07:58:22.000000000 +0200 +++ pgjdbc/org/postgresql/jdbc2/AbstractJdbc2Statement.java 2006-11-17 00:18:57.000000000 +0200 @@ -191,6 +191,9 @@ try { ResultSet rs = AbstractJdbc2Statement.this.createResultSet(fromQuery, fields, tuples, cursor); + if (preparedQuery != null) { + preparedQuery.setFields(fields); + } append(new ResultWrapper(rs)); } catch (SQLException e) diff -urN --exclude=CVS --exclude='*.class' --exclude='*.jar' pgjdbc.clean/org/postgresql/test/jdbc3/ByteaBenchTest.java pgjdbc/org/postgresql/test/jdbc3/ByteaBenchTest.java --- pgjdbc.clean/org/postgresql/test/jdbc3/ByteaBenchTest.java 1970-01-01 02:00:00.000000000 +0200 +++ pgjdbc/org/postgresql/test/jdbc3/ByteaBenchTest.java 2006-11-17 01:24:40.000000000 +0200 @@ -0,0 +1,197 @@ +/*------------------------------------------------------------------------- +* +* Copyright (c) 2004-2005, PostgreSQL Global Development Group +* +* IDENTIFICATION +* $PostgreSQL: pgjdbc/org/postgresql/test/jdbc3/BenchTest.java,v 1.1 2006/07/24 02:31:44 oliver Exp $ +* +*------------------------------------------------------------------------- +*/ +package org.postgresql.test.jdbc3; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Properties; + +import junit.framework.TestCase; + +import org.postgresql.test.TestUtil; + +public class ByteaBenchTest extends TestCase { + + /** + * Number of times the table is queried. + */ + private static final int QUERY_LOOP = 512; + + /** + * Number of rows in temporary table. + */ + private static final int[] SIZES = { 512, 2048, 4096, 16384 , 65536, 1048576 }; + + /** + * How many tries long to prime the jit. + */ + private static final int PRIME_LOOP = 2000; + + /** + * How many times to run the timing and print the times. + */ + private static final int TIMING_LOOP = 10; + + private Connection _conn; + + private String queryString; + + private PreparedStatement query; + + public ByteaBenchTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + _conn = openDB(); + _conn.setAutoCommit(false); + + createTable(); + + query = _conn.prepareStatement("SELECT val FROM hold WHERE key=?"); + } + + protected Connection openDB() throws Exception { + Properties p = new Properties(); + p.setProperty("prepareThreshold", "1"); + return TestUtil.openDB(p); + } + + private void createTable() throws SQLException { + Statement stmt = _conn.createStatement(); + stmt.execute("CREATE TEMP TABLE hold(key int, val bytea) " + + " ON COMMIT PRESERVE ROWS"); + stmt.close(); + + PreparedStatement insert = + _conn.prepareStatement("INSERT INTO hold (key, val) VALUES (?, ?)"); + + StringBuilder sb = new StringBuilder(); + sb.append("INSERT INTO hold (key"); + for (int i=0; i<SIZES.length; ++i) { + insert.setInt(1, SIZES[i]); + insert.setBytes(2, createBytes(SIZES[i])); + assertEquals(1, insert.executeUpdate()); + } + insert.close(); + _conn.commit(); + } + + private byte[] createBytes(int len) { + byte[] b = new byte[len]; + for (int i = 0; i < b.length; ++i) { + b[i] = (byte) i; + } + return b; + } + + protected void tearDown() throws SQLException { + query.close(); + dropTable(); + TestUtil.closeDB(_conn); + } + + private void dropTable() { + Statement stmt; + try { + stmt = _conn.createStatement(); + stmt.execute("DROP TABLE hold"); + stmt.close(); + _conn.commit(); + } catch (SQLException e) { + // ignored + } + } + + public void testBenchmark() throws Exception { + System.out.print("Warming JIT for benchmark loop: "); + int printed = -1; + for (int i=0; i<PRIME_LOOP; ++i) { + for (int s = 0; s < SIZES.length; ++s) + query(SIZES[s]); + int readyNess = (PRIME_LOOP - i - 1) * 10 / PRIME_LOOP; + if (readyNess != printed) { + printed = readyNess; + System.out.print(printed); + clearGC(); + } + } + System.out.println(); + + // let jit do it's magic and flush all initial garbage + clearGC(); + + System.in.read(); + + double[] best = new double[SIZES.length]; + long[] maxMemUse = new long[SIZES.length]; + for (int s = 0; s < SIZES.length; ++s) { + int size = SIZES[s]; + long start, stop; + int queries = QUERY_LOOP; + if (size > 16384) { + queries /= size / 16384; + } else { + queries *= 16384 / size; + } + System.out.printf("Transferring %.1fMB of data in %.1fkb chunks\n", + size * queries / 1024.0 / 1024, size / 1024.0); + for (int i=0; i<TIMING_LOOP; ++i) { + start = System.currentTimeMillis(); + for (int j=0; j<queries; ++j) { + query(size); + } + stop = System.currentTimeMillis(); + _conn.commit(); + + Runtime rt = Runtime.getRuntime(); + long memUse = rt.totalMemory() - rt.freeMemory(); + if (memUse > maxMemUse[s]) { + maxMemUse[s] = memUse; + } + clearGC(); + + double speed = queries * 1000.0 / (stop-start) * size; + speed /= 1024 * 1024; + if (speed > best[s]) { + best[s] = speed; + } + System.out.printf(" %7db speed:%5.1fMB/s (best %5.1fMB/s) memory: %5.1fMB (worst %5.1fMB)\n", + size, speed, best[s], memUse/1024.0/1024.0, maxMemUse[s]/1024.0/1024.0); + } + } + + for (int s = 0; s < SIZES.length; ++s) { + System.out.printf("%7db speed: %5.1fMB/s memory: %5.1fMB\n", + SIZES[s], + best[s], maxMemUse[s]/1024.0/1024.0); + } + } + + private void clearGC() throws InterruptedException { + Thread.sleep(10); + System.runFinalization(); + System.gc(); + Thread.sleep(90); + } + + private void query(int size) throws SQLException { + query.setInt(1, size); + ResultSet rs = query.executeQuery(); + assertTrue(rs.next()); + byte[] bytes = rs.getBytes(1); + assertEquals(size, bytes.length); + assertFalse(rs.next()); + rs.close(); + } +}

view thread (2+ messages)  latest in thread

Message-ID: <1163715629.8932.22.camel@mokki.local>
Permalink:  ../1163715629.8932.22.camel@mokki.local/
Also on:    postgresql.org/message-id/1163715629.8932.22.camel@mokki.local

 ·  · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-jdbc@postgresql.org
  Cc: mikko.tiihonen@iki.fi
  Subject: Re: ResultSet.getBytes() of bytea speedup batch
  In-Reply-To: <1163715629.8932.22.camel@mokki.local>
  References: <1163715629.8932.22.camel@mokki.local>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox