From 5170da8fd7d4287f6e3530a62b2070cd7901c8cc Mon Sep 17 00:00:00 2001 From: Andrew Steinborn Date: Sun, 9 May 2021 02:57:01 -0400 Subject: [PATCH] Improve writeVarInt inlining by peeling the two most common cases --- .../proxy/protocol/ProtocolUtils.java | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/proxy/src/main/java/com/velocitypowered/proxy/protocol/ProtocolUtils.java b/proxy/src/main/java/com/velocitypowered/proxy/protocol/ProtocolUtils.java index ee3482c9d..7ae34b9db 100644 --- a/proxy/src/main/java/com/velocitypowered/proxy/protocol/ProtocolUtils.java +++ b/proxy/src/main/java/com/velocitypowered/proxy/protocol/ProtocolUtils.java @@ -120,6 +120,19 @@ public enum ProtocolUtils { * @param value the integer to write */ public static void writeVarInt(ByteBuf buf, int value) { + // Peel the one and two byte count cases explicitly as they are the most common VarInt sizes + // that the proxy will write, to improve inlining. + if ((value & (0xFFFFFFFF << 7)) == 0) { + buf.writeByte(value); + } else if ((value & (0xFFFFFFFF << 14)) == 0) { + int w = (value & 0x7F | 0x80) << 8 | (value >>> 7); + buf.writeShort(w); + } else { + writeVarIntFull(buf, value); + } + } + + private static void writeVarIntFull(ByteBuf buf, int value) { // See https://steinborn.me/posts/performance/how-fast-can-you-write-a-varint/ if ((value & (0xFFFFFFFF << 7)) == 0) { buf.writeByte(value); @@ -135,7 +148,7 @@ public enum ProtocolUtils { buf.writeInt(w); } else { int w = (value & 0x7F | 0x80) << 24 | ((value >>> 7) & 0x7F | 0x80) << 16 - | ((value >>> 14) & 0x7F | 0x80) << 8 | ((value >>> 21) & 0x7F | 0x80); + | ((value >>> 14) & 0x7F | 0x80) | ((value >>> 21) & 0x7F | 0x80); buf.writeInt(w); buf.writeByte(value >>> 28); }