From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: astei Date: Sat, 1 Oct 2022 09:56:47 +0200 Subject: [PATCH] PaperPR Optimize VarInts Original license: GPLv3 Original project: https://github.com/PaperMC/Velocity Paper pull request: https://github.com/PaperMC/Paper/pull/8418 diff --git a/src/main/java/net/minecraft/network/FriendlyByteBuf.java b/src/main/java/net/minecraft/network/FriendlyByteBuf.java index a7b6e22daf64abca311bc5771192a3c09368537f..c264aa4c8db4d68c75364206893e6aff7f2e483e 100644 --- a/src/main/java/net/minecraft/network/FriendlyByteBuf.java +++ b/src/main/java/net/minecraft/network/FriendlyByteBuf.java @@ -89,15 +89,18 @@ public class FriendlyByteBuf extends ByteBuf { this.source = parent; } - public static int getVarIntSize(int value) { - for (int j = 1; j < 5; ++j) { - if ((value & -1 << j * 7) == 0) { - return j; - } + // Paper start - Optimize VarInts + private static final int[] VARINT_EXACT_BYTE_LENGTHS = new int[33]; + static { + for (int i = 0; i <= 32; ++i) { + VARINT_EXACT_BYTE_LENGTHS[i] = (int) Math.ceil((31d - (i - 1)) / 7d); } - - return 5; + VARINT_EXACT_BYTE_LENGTHS[32] = 1; // Special case for the number 0. + } + public static int getVarIntSize(int value) { + return VARINT_EXACT_BYTE_LENGTHS[Integer.numberOfLeadingZeros(value)]; // Paper - Optimize VarInts } + // Paper end - Optimize VarInts public static int getVarLongSize(long value) { for (int j = 1; j < 10; ++j) { @@ -505,7 +508,22 @@ public class FriendlyByteBuf extends ByteBuf { return new UUID(this.readLong(), this.readLong()); } + // Paper start - Optimize VarInts public FriendlyByteBuf writeVarInt(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) { + writeByte(value); + } else if ((value & (0xFFFFFFFF << 14)) == 0) { + int w = (value & 0x7F | 0x80) << 8 | (value >>> 7); + writeShort(w); + } else { + writeVarInt_(value); + } + return this; + } + public FriendlyByteBuf writeVarInt_(int value) { + // Paper end - Optimize VarInts while ((value & -128) != 0) { this.writeByte(value & 127 | 128); value >>>= 7;