Skip to content

Commit

Permalink
Polishing.
Browse files Browse the repository at this point in the history
Replace String.format(…) with our own digit rendering and padding to reduce computation on hot code paths.

[resolves #558][#556]

Signed-off-by: Mark Paluch <mpaluch@vmware.com>
  • Loading branch information
mp911de committed Nov 9, 2022
1 parent 44d8d76 commit dcbc951
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 6 deletions.
16 changes: 11 additions & 5 deletions src/main/java/io/r2dbc/postgresql/codec/NumericDecodeUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -111,18 +111,24 @@ public static BigDecimal decodeBinary(ByteBuf byteBuf) {
digits[i] = byteBuf.readShort();
}

StringBuilder sb = new StringBuilder();
StringBuilder sb = new StringBuilder((sign != 0 ? 1 : 0) + 2 + (digits.length * 4));
if (sign != 0) {
sb.append("-");
}
sb.append("0.");
for (short digit : digits) {
sb.append(String.format("%04d", digit));
String rendered = "" + digit;
int padded = rendered.length();

while (padded < 4) {
sb.append("0");
padded++;
}

sb.append(rendered);
}

return new BigDecimal(sb.toString())
.movePointRight((weight + 1) * 4)
.setScale(scale, RoundingMode.DOWN);
return new BigDecimal(sb.toString()).movePointRight((weight + 1) * 4).setScale(scale, RoundingMode.DOWN);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,10 @@ void bigDecimal() {
testCodec(BigDecimal.class, new BigDecimal("-1"), "NUMERIC");
testCodec(BigDecimal.class, new BigDecimal("10000.0000023"), "NUMERIC");
testCodec(BigDecimal.class, new BigDecimal("10010.1200023"), "NUMERIC");
testCodec(BigDecimal.class, new BigDecimal("-10010.1200023"), "NUMERIC");
testCodec(BigDecimal.class, new BigDecimal("2000010010.1200023"), "NUMERIC");
testCodec(BigDecimal.class, new BigDecimal("0.1200023"), "NUMERIC");
testCodec(BigDecimal.class, new BigDecimal("-0.1200023"), "NUMERIC");
testCodec(BigDecimal.class, new BigDecimal("0"), "NUMERIC");
testCodec(BigDecimal.class, new BigDecimal("100"), "INT2");
testCodec(BigDecimal.class, new BigDecimal("100"), "INT4");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@

import static org.assertj.core.api.Assertions.assertThat;

/**
* Unit tests for {@link NumericDecodeUtils}.
*/
class NumericDecodeUtilsTest {

static Stream<Object[]> bigDecimalValues() {
Expand Down Expand Up @@ -82,6 +85,7 @@ void decodeBinary2(BigDecimal value) {
ByteBuf byteBuf = TestByteBufAllocator.TEST.buffer();
byteBuf.writeBytes(ByteConverter.numeric(value));
assertThat(NumericDecodeUtils.decodeBinary(byteBuf)).isEqualByComparingTo(value);
byteBuf.release();
}

}
}

0 comments on commit dcbc951

Please sign in to comment.