From 33da6432202075cad3f91881e859778f89a9765c Mon Sep 17 00:00:00 2001 From: Bryan Duxbury Date: Mon, 5 Apr 2010 16:28:21 +0000 Subject: [PATCH] THRIFT-754. java: Improvements to varint reading in Compact Protocol This patch makes readVarint32 about 30% faster and readVarint64 about 25% faster (when using transports that support direct buffer access). git-svn-id: https://svn.apache.org/repos/asf/incubator/thrift/trunk@930898 13f79535-47bb-0310-9956-ffa450edef68 --- .../thrift/protocol/TCompactProtocol.java | 50 ++++++++++++++++--- 1 file changed, 42 insertions(+), 8 deletions(-) diff --git a/lib/java/src/org/apache/thrift/protocol/TCompactProtocol.java b/lib/java/src/org/apache/thrift/protocol/TCompactProtocol.java index 7cc4f61c..f4979423 100755 --- a/lib/java/src/org/apache/thrift/protocol/TCompactProtocol.java +++ b/lib/java/src/org/apache/thrift/protocol/TCompactProtocol.java @@ -665,9 +665,29 @@ public final class TCompactProtocol extends TProtocol { * if there is another byte to follow. This can read up to 5 bytes. */ private int readVarint32() throws TException { - // if the wire contains the right stuff, this will just truncate the i64 we - // read and get us the right sign. - return (int)readVarint64(); + int result = 0; + int shift = 0; + if (trans_.getBytesRemainingInBuffer() >= 5) { + byte[] buf = trans_.getBuffer(); + int pos = trans_.getBufferPosition(); + int off = 0; + while (true) { + byte b = buf[pos+off]; + result |= (int) (b & 0x7f) << shift; + if ((b & 0x80) != 0x80) break; + shift += 7; + off++; + } + trans_.consumeBuffer(off+1); + } else { + while (true) { + byte b = readByte(); + result |= (int) (b & 0x7f) << shift; + if ((b & 0x80) != 0x80) break; + shift += 7; + } + } + return result; } /** @@ -677,11 +697,25 @@ public final class TCompactProtocol extends TProtocol { private long readVarint64() throws TException { int shift = 0; long result = 0; - while (true) { - byte b = readByte(); - result |= (long) (b & 0x7f) << shift; - if ((b & 0x80) != 0x80) break; - shift +=7; + if (trans_.getBytesRemainingInBuffer() >= 10) { + byte[] buf = trans_.getBuffer(); + int pos = trans_.getBufferPosition(); + int off = 0; + while (true) { + byte b = buf[pos+off]; + result |= (long) (b & 0x7f) << shift; + if ((b & 0x80) != 0x80) break; + shift += 7; + off++; + } + trans_.consumeBuffer(off+1); + } else { + while (true) { + byte b = readByte(); + result |= (long) (b & 0x7f) << shift; + if ((b & 0x80) != 0x80) break; + shift +=7; + } } return result; } -- 2.17.1