Received: from localhost (wm.hub.org [200.46.204.128]) by postgresql.org (Postfix) with ESMTP id DFE0C9FB221 for ; Fri, 29 Sep 2006 19:48:18 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.128]) (amavisd-new, port 10024) with ESMTP id 20240-09 for ; Fri, 29 Sep 2006 22:48:05 +0000 (UTC) X-Greylist: delayed 00:31:29.755168 by SQLgrey- Received: from fep32-app.kolumbus.fi (fep32-0.kolumbus.fi [193.229.0.63]) by postgresql.org (Postfix) with ESMTP id 914209FB1F0 for ; Fri, 29 Sep 2006 19:48:04 -0300 (ADT) Received: from dual.local ([88.115.1.94]) by fep14-app.kolumbus.fi with ESMTP id <20060929215606.LBAR1423.fep14-app.kolumbus.fi@dual.local> for ; Sat, 30 Sep 2006 00:56:06 +0300 Subject: Query ResultSet parsing speedup patch (resend) From: Mikko Tiihonen To: pgsql-jdbc@postgresql.org Content-Type: multipart/mixed; boundary="=-0wAUpKkri8AIU52+wn8s" Date: Sat, 30 Sep 2006 01:01:13 +0300 Message-Id: <1159567273.19055.7.camel@dual.local> Mime-Version: 1.0 X-Mailer: Evolution 2.6.2 X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0.135 tagged_above=0 required=5 tests=FORGED_RCVD_HELO X-Spam-Level: X-Archive-Number: 200609/164 X-Sequence-Number: 15882 --=-0wAUpKkri8AIU52+wn8s Content-Type: text/plain Content-Transfer-Encoding: 7bit Hi, This is a resend since I did not get any feedback to this patch when I sent it two months ago. Could someone at least have some recommendations what I should do to get this patch evaluated or even applied to the official source. Also, could someone update the CVS info page (http://jdbc.postgresql.org/development/cvs.html) to point to the new pgfoundry ? --- I tried to optimise the parsing of ResultSets from the network stream, especially int and long values, but also a bit for String values. The attached patch gives upto 40% speedup when parsing larger queries containing equal amounts of int4, int8 or varchar(16) columns if the system is cpu bound. The speedup comes mainly from avoiding creation of useless objects and avoiding useless byte[] copies. In more real-life scenarios the speedup will be much smaller. The patch also contains the test code which I used to test the performance (BenchTest.java). The benchmark results are: unpatched 503 jdbc driver: speed: 180.18 memory: 36.8MB patched 503 jdbc driver: speed: 261.44 memory: 19.6MB +40% -40% The benchmark was run on Java6rc build 100 with postgresql 8.1.4 running on localhost with Athlon64 2x2GHz, 64bit mode. If the patch is accepted I can try to do similar optimisations for other fields. --- What the patch does: Parsing string: old way: read byte[] containing the exact bytes of a string new way: create a string directly from network buffer with start and end index Parsing numbers: old way: create a string that contains the number and use Integer.parseInt new way: parse the number directly from bytes Exact changes explained: new class VisibleBufferedInputStream: - replaced java.io.BufferedInputStream with faster implementation * no synchronisation * allows direct access to the buffer byte[] contents which helps to avoiding useless copies when converting to String * has method for scanning the length of next null terminated string PGStream: - uses VisibleBuffereInputStream * faster implementations for for ReceiveIntegerR and ReceiveString AbstractJdbc2ResultSet - parses int and long values directly from byte[] -> number instead of first creating a throw-away string - if the fast conversion fails or if the current charset is not safe for the optimisation then uses the old way to parse - also very minor optimisation to getFixedString to optimise for non-money string types Encoding: - uses HashMap instead of synchronised Hashtable - does not do two queries to encodings map when obtaining database encoding - added method to check if the numbers match ASCII charset locations (all currently listed charsets match) --=-0wAUpKkri8AIU52+wn8s Content-Disposition: attachment; filename=postgresql-resultset-parsing-speedup.patch Content-Type: text/x-patch; name=postgresql-resultset-parsing-speedup.patch; charset=us-ascii Content-Transfer-Encoding: 7bit diff -u -r1.19 PGStream.java --- org/postgresql/core/PGStream.java 29 Apr 2006 13:30:23 -0000 1.19 +++ org/postgresql/core/PGStream.java 29 Sep 2006 20:56:19 -0000 @@ -9,7 +9,6 @@ */ package org.postgresql.core; -import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.InputStream; import java.io.OutputStream; @@ -37,7 +36,7 @@ private final int port; private Socket connection; - private InputStream pg_input; + private VisibleBufferedInputStream pg_input; private OutputStream pg_output; private byte[] streamBuffer; @@ -103,7 +102,7 @@ connection.setTcpNoDelay(true); // Buffer sizes submitted by Sverre H Huseby - pg_input = new BufferedInputStream(connection.getInputStream(), 8192); + pg_input = new VisibleBufferedInputStream(connection.getInputStream(), 8192); pg_output = new BufferedOutputStream(connection.getOutputStream(), 8192); if (encoding != null) @@ -268,14 +267,15 @@ */ public int ReceiveIntegerR(int siz) throws IOException { + if (!pg_input.ensureBytes(siz)) { + throw new EOFException(); + } int n = 0; for (int i = 0 ; i < siz ; i++) { - int b = pg_input.read(); + int b = pg_input.readRaw() & 0xFF; - if (b < 0) - throw new EOFException(); n = b | (n << 8); } @@ -290,8 +290,6 @@ } - private byte[] byte_buf = new byte[8*1024]; - /** * Receives a fixed-size string from the backend. * @@ -299,11 +297,14 @@ * @return the decoded string */ public String ReceiveString(int len) throws IOException { - if (len > byte_buf.length) - byte_buf = new byte[len]; + if (!pg_input.ensureBytes(len)) { + throw new EOFException(); + } - Receive(byte_buf, 0, len); - return encoding.decode(byte_buf, 0, len); + String res = encoding.decode(pg_input.getBuffer(), pg_input.getIndex(), + len); + pg_input.skip(len); + return res; } /** @@ -315,36 +316,11 @@ */ public String ReceiveString() throws IOException { - int i = 0; - byte[] rst = byte_buf; - int buflen = rst.length; - - while (true) - { - int c = pg_input.read(); - - if (c < 0) - throw new EOFException(); - - if (c == 0) - break; - - if (i == buflen) - { - // Grow the buffer. - buflen *= 2; // 100% bigger - if (buflen <= 0) // Watch for overflow - throw new IOException("Impossibly long string"); - - byte[] newrst = new byte[buflen]; - System.arraycopy(rst, 0, newrst, 0, i); - rst = newrst; - } - - rst[i++] = (byte)c; - } - - return encoding.decode(rst, 0, i); + int len = pg_input.scanCStringLength(); + String res = encoding.decode(pg_input.getBuffer(), pg_input.getIndex(), + len - 1); + pg_input.skip(len); + return res; } /** diff -u -r1.21 Encoding.java --- org/postgresql/core/Encoding.java 4 Jul 2005 02:18:32 -0000 1.21 +++ org/postgresql/core/Encoding.java 29 Sep 2006 20:56:20 -0000 @@ -16,7 +16,7 @@ import java.io.OutputStreamWriter; import java.io.Writer; import java.io.IOException; -import java.util.Hashtable; +import java.util.HashMap; /** * Representation of a particular character encoding. @@ -28,7 +28,7 @@ /* * Preferred JVM encodings for backend encodings. */ - private static final Hashtable encodings = new Hashtable(); + private static final HashMap encodings = new HashMap(); static { //Note: this list should match the set of supported server @@ -75,10 +75,22 @@ } private final String encoding; + private final boolean fastASCIINumbers; protected Encoding(String encoding) { this.encoding = encoding; + fastASCIINumbers = testAsciiNumbers(); + } + + /** + * Returns true if this encoding has characters + * '-' and '0'..'9' in exactly same posision as ascii. + * + * @return true if the bytes can be scanned directly for ascii numbers. + */ + public boolean hasAsciiNumbers() { + return fastASCIINumbers; } /** @@ -115,9 +127,9 @@ // encoding in the JVM we use that. Otherwise we fall back // to the default encoding of the JVM. - if (encodings.containsKey(databaseEncoding)) + String[] candidates = (String[]) encodings.get(databaseEncoding); + if (candidates != null) { - String[] candidates = (String[]) encodings.get(databaseEncoding); for (int i = 0; i < candidates.length; i++) { if (isAvailable(candidates[i])) @@ -254,4 +266,28 @@ public String toString() { return (encoding == null ? "" : encoding); } + + /** + * Checks weather this encoding is compatible with ASCII for the number + * characters '-' and '0'..'9'. Where compatible means that they are encoded + * with exactly same values. + * + * @return If faster ASCII number parsing can be used with this encoding. + */ + private boolean testAsciiNumbers() { + // TODO: test all postgres supported encoding to see if there are + // any which do _not_ have ascii numbers in same location + // at least all the encoding listed in the encodings hashmap have + // working ascii numbers + try { + String test = "-0123456789"; + byte[] bytes = encode(test); + String res = new String(bytes, "US-ASCII"); + return test.equals(res); + } catch (java.io.UnsupportedEncodingException e) { + return false; + } catch (IOException e) { + return false; + } + } } diff -u -r1.84 AbstractJdbc2ResultSet.java --- org/postgresql/jdbc2/AbstractJdbc2ResultSet.java 6 Aug 2006 18:11:33 -0000 1.84 +++ org/postgresql/jdbc2/AbstractJdbc2ResultSet.java 29 Sep 2006 20:56:20 -0000 @@ -1960,13 +1959,148 @@ public int getInt(int columnIndex) throws SQLException { + Encoding encoding = connection.getEncoding(); + if (encoding.hasAsciiNumbers()) { + try { + return getFastInt(columnIndex); + } catch (NumberFormatException ex) { + } + } return toInt( getFixedString(columnIndex) ); } public long getLong(int columnIndex) throws SQLException { + Encoding encoding = connection.getEncoding(); + if (encoding.hasAsciiNumbers()) { + try { + return getFastLong(columnIndex); + } catch (NumberFormatException ex) { + } + } return toLong( getFixedString(columnIndex) ); } + + private static final NumberFormatException FAST_NUMBER_FAILED = + new NumberFormatException(); + + /** + * Optimised byte[] to number parser. + * + * @param columnIndex The column to parse. + * @return The parsed number. + * @throws SQLException If an error occurs while fetching column. + * @throws NumberFormatException If the number is invalid or the + * out of range for fast parsing. The value must then be parsed by + * {@link #toLong(String)}. + */ + private long getFastLong(int columnIndex) throws SQLException, + NumberFormatException { + + checkResultSet( columnIndex ); + + columnIndex--; + if (this_row[columnIndex] == null) { + return 0; // SQL NULL + } + + byte[] bytes = this_row[columnIndex]; + + if (bytes.length == 0) { + throw FAST_NUMBER_FAILED; + } + + long val = 0; + int start; + boolean neg; + if (bytes[0] == '-') { + neg = true; + start = 1; + if (bytes.length > 19) { + throw FAST_NUMBER_FAILED; + } + } else { + start = 0; + neg = false; + if (bytes.length > 18) { + throw FAST_NUMBER_FAILED; + } + } + + while (start < bytes.length) { + byte b = bytes[start++]; + if (b < '0' || b > '9') { + throw FAST_NUMBER_FAILED; + } + + val *= 10; + val += b - '0'; + } + + if (neg) { + val = -val; + } + + return val; + } + + /** + * Optimised byte[] to number parser. + * + * @param columnIndex The column to parse. + * @return The parsed number. + * @throws SQLException If an error occurs while fetching column. + * @throws NumberFormatException If the number is invalid or the + * out of range for fast parsing. The value must then be parsed by + * {@link #toLong(String)}. + */ + private int getFastInt(int columnIndex) throws SQLException { + checkResultSet( columnIndex ); + + columnIndex--; + if (this_row[columnIndex] == null) { + return 0; // SQL NULL + } + + byte[] bytes = this_row[columnIndex]; + + if (bytes.length == 0) { + throw FAST_NUMBER_FAILED; + } + + int val = 0; + int start; + boolean neg; + if (bytes[0] == '-') { + neg = true; + start = 1; + if (bytes.length > 9) { + throw FAST_NUMBER_FAILED; + } + } else { + start = 0; + neg = false; + if (bytes.length > 8) { + throw FAST_NUMBER_FAILED; + } + } + + while (start < bytes.length) { + byte b = bytes[start++]; + if (b < '0' || b > '9') { + throw FAST_NUMBER_FAILED; + } + + val *= 10; + val += b - '0'; + } + + if (neg) { + val = -val; + } + + return val; + } public float getFloat(int columnIndex) throws SQLException { @@ -2361,24 +2495,31 @@ */ public String getFixedString(int col) throws SQLException { - String s = getString(col); - // Handle SQL Null wasNullFlag = (this_row[col - 1] == null); if (wasNullFlag) return null; + String s = getString(col); + // if we don't have at least 2 characters it can't be money. if (s.length() < 2) return s; // Handle Money char ch = s.charAt(0); + + // optimise for non-money type: return immediately with one check + // if the first char cannot be '(', '$' or '-' + if (ch > '-') { + return s; + } + if (ch == '(') { s = "-" + PGtokenizer.removePara(s).substring(1); } - if (ch == '$') + else if (ch == '$') { s = s.substring(1); } diff -u --new-file -r1.0 org/postgresql/core/VisibleBufferedInputStream.java --- org/postgresql/core/VisibleBufferedInputStream.java 1970-01-01 02:00:00.000000000 +0200 +++ org/postgresql/core/VisibleBufferedInputStream.java 2006-09-30 00:04:56.000000000 +0300 @@ -0,0 +1,293 @@ +/*------------------------------------------------------------------------- + * + * Copyright (c) 2006, PostgreSQL Global Development Group + * + * IDENTIFICATION + * $PostgreSQL: pgjdbc/org/postgresql/core/VisibleBufferedInputSTream.java,v 1.0 2006/07/24 13:30:23 jurka Exp $ + * + *------------------------------------------------------------------------- + */ +package org.postgresql.core; + +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; + +/** + * A faster version of BufferedInputStream. Does no synchronisation and + * allows direct access to the used byte[] buffer. + * + * @author Mikko Tiihonen + */ +public class VisibleBufferedInputStream extends InputStream { + + /** + * If a direct read to byte array is called that would require + * a smaller read from the wrapped stream that MINIMUM_READ then + * first fill the buffer and serve the bytes from there. Larger + * reads are directly done to the provided byte array. + */ + private static final int MINIMUM_READ = 1024; + + /** + * In how large spans is the C string zero-byte scanned. + */ + private static final int STRING_SCAN_SPAN = 1024; + + /** + * The wrapped input stream. + */ + private final InputStream wrapped; + + /** + * The buffer. + */ + private byte[] buffer; + + /** + * Current read position in the buffer. + */ + private int index; + + /** + * How far is the buffer filled with valid data. + */ + private int endIndex; + + /** + * Creates a new buffer around the given stream. + * + * @param in The stream to buffer. + * @param bufferSize The initial size of the buffer. + */ + public VisibleBufferedInputStream(InputStream in, int bufferSize) { + wrapped = in; + buffer = new byte[bufferSize < MINIMUM_READ ? + MINIMUM_READ : bufferSize]; + } + + /** + * {@inheritDoc} + */ + public int read() throws IOException { + if (ensureBytes(1)) { + return buffer[index++] & 0xFF; + } + return -1; + } + + /** + * Reads byte from the buffer without any checks. This method never + * reads from the underlaying stream. + * Before calling this method the {@link #ensureBytes} method must + * have been called. + * + * @return The next byte from the buffer. + * @throws ArrayIndexOutOfBoundsException If ensureBytes was not called + * to make sure the buffer contains the byte. + */ + public byte readRaw() { + return buffer[index++]; + } + + /** + * Ensures that the buffer contains at least n bytes. + * This method invalidates the buffer and index fields. + * + * @param n The amount of bytes to ensure exists in buffer + * @return true if required bytes are available and false if EOF + * @throws IOException If reading of the wrapped stream failed. + */ + public boolean ensureBytes(int n) throws IOException { + int required = n - endIndex + index; + while (required > 0) { + if (!readMore(required)) { + return false; + } + required = n - endIndex + index; + } + return true; + } + + /** + * Reads more bytes into the buffer. + * + * @param wanted How much should be at least read. + * @return True if at least some bytes were read. + * @throws IOException If reading of the wrapped stream failed. + */ + private boolean readMore(int wanted) throws IOException { + if (endIndex == index) { + index = 0; + endIndex = 0; + } + int canFit = buffer.length - endIndex; + if (canFit < wanted) { + // would the wanted bytes fit if we compacted the buffer + // and still leave some slack + if (index + canFit > wanted + MINIMUM_READ) { + compact(); + } else { + doubleBuffer(); + } + canFit = buffer.length - endIndex; + } + int read = wrapped.read(buffer, endIndex, canFit); + if (read < 0) { + return false; + } + endIndex += read; + return true; + } + + /** + * Doubles the size of the buffer. + */ + private void doubleBuffer() { + byte[] buf = new byte[buffer.length * 2]; + moveBufferTo(buf); + buffer = buf; + } + + /** + * Compacts the unread bytes of the buffer to the beginning of the buffer. + */ + private void compact() { + moveBufferTo(buffer); + } + + /** + * Moves bytes from the buffer to the begining of the destination buffer. + * Also sets the index and endIndex variables. + * + * @param dest The destination buffer. + */ + private void moveBufferTo(byte[] dest) { + int size = endIndex - index; + System.arraycopy(buffer, index, dest, 0, size); + index = 0; + endIndex = size; + } + + /** + * {@inheritDoc} + */ + public int read(byte to[], int off, int len) throws IOException { + if ((off | len | (off + len) | (to.length - (off + len))) < 0) { + throw new IndexOutOfBoundsException(); + } else if (len == 0) { + return 0; + } + + // if the read would go to wrapped stream, but would result + // in a small read then try read to the buffer instead + int avail = endIndex - index; + if (len - avail < MINIMUM_READ) { + ensureBytes(len); + avail = endIndex - index; + } + + // first copy from buffer + if (avail > 0) { + if (len <= avail) { + System.arraycopy(buffer, index, to, off, len); + index += len; + return len; + } + System.arraycopy(buffer, index, to, off, avail); + len -= avail; + off += avail; + } + int read = avail; + + // good place to reset index because the buffer is fully drained + index = 0; + endIndex = 0; + + // then directly from wrapped stream + do { + int r = wrapped.read(to, off, len); + if (r <= 0) { + return (read == 0) ? r : read; + } + read += r; + off += r; + len -= r; + } while (len > 0); + + return read; + } + + /** + * {@inheritDoc} + */ + public long skip(long n) throws IOException { + int avail = endIndex - index; + if (avail >= n) { + index += n; + return n; + } + n -= avail; + index = 0; + endIndex = 0; + return wrapped.skip(n); + } + + /** + * {@inheritDoc} + */ + public int available() throws IOException { + int avail = endIndex - index; + return avail > 0 ? avail : wrapped.available(); + } + + /** + * {@inheritDoc} + */ + public void close() throws IOException { + wrapped.close(); + } + + /** + * Returns direct handle to the used buffer. Use the {@link #ensureBytes} + * to prefill required bytes the buffer and {@link #getIndex} to fetch + * the current position of the buffer. + * + * @return The underlaying buffer. + */ + public byte[] getBuffer() { + return buffer; + } + + /** + * Returns the current read position in the buffer. + * + * @return the current read position in the buffer. + */ + public int getIndex() { + return index; + } + + /** + * Scans the length of the next null terminated string (C-style string) from + * the stream. + * + * @return The length of the next null terminated string. + * @throws IOException If reading of stream fails. + * @throws EOFxception If the stream did not contain any null terminators. + */ + public int scanCStringLength() throws IOException { + int pos = index; + for (;;) { + while (pos < endIndex) { + if (buffer[pos++] == '\0') { + return pos - index; + } + } + if (!readMore(STRING_SCAN_SPAN)) { + throw new EOFException(); + } + pos = index; + } + } +} diff -u --new-file -r 1.0 org/postgresql/test/jdbc3/BenchTest.java --- org/postgresql/test/jdbc3/BenchTest.java 1970-01-01 02:00:00.000000000 +0200 +++ org/postgresql/test/jdbc3/BenchTest.java 2006-09-30 00:04:53.000000000 +0300 @@ -0,0 +1,225 @@ +/*------------------------------------------------------------------------- +* +* 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.*; + +import junit.framework.TestCase; +import org.postgresql.test.TestUtil; + +public class BenchTest extends TestCase { + + /** + * Number of times the table is queried. + */ + private static final int QUERY_LOOP = 40; + + /** + * Number of columns in each row. + */ + private static final int COLS = 9; + + /** + * Number of rows in temporary table. + */ + private static final int ROWS = 20; + + /** + * How many tries long to prime the jit. + */ + private static final int PRIME_LOOP = 500; + + /** + * How many times to run the timing and print the times. + */ + private static final int TIMING_LOOP = 50; + + private Connection _conn; + + private PreparedStatement insert; + + private String queryString; + + private PreparedStatement query; + + public BenchTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + _conn = TestUtil.openDB(); + createTable(); + + _conn.setAutoCommit(false); + + StringBuilder sb = new StringBuilder(); + sb.append("INSERT INTO hold (key"); + for (int i=0; i maxMemUse) { + maxMemUse = memUse; + } + clearGC(); + + double speed = QUERY_LOOP * 1000.0 / (stop-start); + if (speed > best) { + best = speed; + } + System.out.printf("speed: %7.2f (best %7.2f) memory: %5.1fMB (worst %5.1fMB)\n", + speed, best, memUse/1024.0/1024.0, maxMemUse/1024.0/1024.0); + } + } + + private void clearGC() throws InterruptedException { + Thread.sleep(10); + System.runFinalization(); + System.gc(); + Thread.sleep(90); + } + + private void query() throws SQLException { + for (int i=0; i<20; ++i) { + ResultSet rs = query.executeQuery(); + for (int r=0; r