pg.ddx.io  pgsql-jdbc@postgresql.org mailing list archive  
help / color / mirror / Atom feed
ResultSet.getBytes() of bytea speedup batch
2+ messages / 2 participants
[nested] [flat]

* ResultSet.getBytes() of bytea speedup batch
@ 2006-11-16 22:20  Mikko Tiihonen <mikko.tiihonen@iki.fi>
  0 siblings, 1 reply; 2+ messages in thread

From: Mikko Tiihonen @ 2006-11-16 22:20 UTC (permalink / raw)
  To: pgsql-jdbc

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(); + } +}
^ permalink raw reply [nested|flat] 2+ messages in thread

* Re: ResultSet.getBytes() of bytea speedup batch
@ 2006-11-19 20:31  Heikki Linnakangas <heikki@enterprisedb.com>
  parent: Mikko Tiihonen <mikko.tiihonen@iki.fi>
  0 siblings, 0 replies; 2+ messages in thread

From: Heikki Linnakangas @ 2006-11-19 20:31 UTC (permalink / raw)
  To: Mikko Tiihonen <mikko.tiihonen@iki.fi>; +Cc: pgsql-jdbc

Mikko Tiihonen wrote:
> 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.

Impressive results!

> 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

I'm getting similar results, though the drop after 65536b is even steeper:

cvs:
     [junit]     512b speed:   1.8MB/s memory:   2.5MB
     [junit]    2048b speed:   5.0MB/s memory:   2.0MB
     [junit]    4096b speed:   7.5MB/s memory:   2.0MB
     [junit]   16384b speed:  11.8MB/s memory:   2.4MB
     [junit]   65536b speed:  12.6MB/s memory:   2.4MB
     [junit] 1048576b speed:   5.3MB/s memory:   5.8MB

patch:
     [junit]     512b speed:   2.1MB/s memory:   2.0MB
     [junit]    2048b speed:   7.4MB/s memory:   2.2MB
     [junit]    4096b speed:  13.0MB/s memory:   2.1MB
     [junit]   16384b speed:  35.9MB/s memory:   2.3MB
     [junit]   65536b speed:  56.7MB/s memory:   2.0MB
     [junit] 1048576b speed:  17.2MB/s memory:   2.9MB
     [junit] ------------- ---------------- ---------------

Ran on Sun JRE 1.5.0_06, on Intel Core Duo. I sure would like to find an 
explanation for the drop.

> 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?

It could. If the driver issued a Sync message after Describe, and waited 
for the response before sending the Bind, the driver could use the 
information in the RowDesription response. But that would require an 
extra round-trip to the server, so it's probably not worth it in most 
queries.

I wish we could set a default format for each data type in a separate 
message. Like:

SetFormat(oid = 17, format="b")

The server would then send all bytea fields as binary unless otherwise 
stated in the Bind message. It would require a backend-change, of course.

> - 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?

I can't imagine how the fields could change. Seems safe to me.

> @@ -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);
>  }

This is just some leftover crud, right? Couldn't find a reference to 
EMPTY_STATEMENTNAME anywhere.

-- 
   Heikki Linnakangas
   EnterpriseDB   http://www.enterprisedb.com




^ permalink  raw  reply  [nested|flat] 2+ messages in thread


end of thread, other threads:[~2006-11-19 20:31 UTC | newest]

Thread overview: 2+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2006-11-16 22:20 ResultSet.getBytes() of bytea speedup batch Mikko Tiihonen <mikko.tiihonen@iki.fi>
2006-11-19 20:31 ` Heikki Linnakangas <heikki@enterprisedb.com>

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