Received: from localhost (uranus.hub.org [200.46.204.60]) by postgresql.org (Postfix) with ESMTP id 2B5299F946A for ; Thu, 16 Nov 2006 18:51:21 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.60]) (amavisd-new, port 10024) with ESMTP id 74445-05 for ; Thu, 16 Nov 2006 18:51:17 -0400 (AST) X-Greylist: delayed 00:25:56.18837 by SQLgrey- Received: from svr4.postgresql.org (svr4.postgresql.org [66.98.251.159]) by postgresql.org (Postfix) with ESMTP id 71DE59F946B for ; Thu, 16 Nov 2006 18:51:17 -0400 (AST) X-Greylist: domain auto-whitelisted by SQLgrey-1.7.3 Received: from gw02.mail.saunalahti.fi (gw02.mail.saunalahti.fi [195.197.172.116]) by svr4.postgresql.org (Postfix) with ESMTP id 5E13C5AF886 for ; Thu, 16 Nov 2006 22:25:18 +0000 (GMT) Received: from [88.115.1.94] (a88-115-1-94.elisa-laajakaista.fi [88.115.1.94]) (using SSLv3 with cipher RC4-MD5 (128/128 bits)) (No client certificate requested) by gw02.mail.saunalahti.fi (Postfix) with ESMTP id C28051392FC for ; Fri, 17 Nov 2006 00:25:11 +0200 (EET) Subject: ResultSet.getBytes() of bytea speedup batch From: Mikko Tiihonen To: pgsql-jdbc@postgresql.org Content-Type: multipart/mixed; boundary="=-6BKJ9Ld5MJFE6NRWPHbH" Date: Fri, 17 Nov 2006 00:20:29 +0200 Message-Id: <1163715629.8932.22.camel@mokki.local> Mime-Version: 1.0 X-Mailer: Evolution 2.8.1.1 X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200611/82 X-Sequence-Number: 16124 --=-6BKJ9Ld5MJFE6NRWPHbH Content-Type: text/plain Content-Transfer-Encoding: 7bit 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 --=-6BKJ9Ld5MJFE6NRWPHbH Content-Disposition: attachment; filename=getBinary-speedup.patch Content-Type: text/x-patch; name=getBinary-speedup.patch; charset=us-ascii Content-Transfer-Encoding: 7bit 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 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 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(); + } +} --=-6BKJ9Ld5MJFE6NRWPHbH--