From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Martijn Muijsers Date: Mon, 21 Aug 2023 21:46:10 +0200 Subject: [PATCH] Pre-compute VarLong sizes License: GPL-3.0 (https://www.gnu.org/licenses/gpl-3.0.html) Gale - https://galemc.org This patch is based on the following commit: "Reapply "Optimize varint writing"" By: Andrew Steinborn As part of: Velocity (https://github.com/PaperMC/Velocity) Licensed under: GPL-3.0 (https://www.gnu.org/licenses/gpl-3.0.html) * Velocity description * Inspired by the approach described at the bottom of https://richardstartin.github.io/posts/dont-use-protobuf-for-telemetry Given that we do a lot of varint writing as well, this should provide a small performance boost for larger/complex packets whilst not regressing hard on smaller packets. This includes a test to ensure that the behavior is as expected and fixes the initialization loop so that the correct results will be given. Much thanks to @octylFractal for acting as my duck while trying to figure this out. diff --git a/net/minecraft/network/VarLong.java b/net/minecraft/network/VarLong.java index df9a85b19a9767c85f02837af6835f7ddb6c7dc3..ff9d84bf761797a8f695926c3cbb12c07609365d 100644 --- a/net/minecraft/network/VarLong.java +++ b/net/minecraft/network/VarLong.java @@ -9,6 +9,18 @@ public class VarLong { private static final int DATA_BITS_PER_BYTE = 7; public static int getByteSize(long data) { + // Gale start - Velocity - pre-compute VarInt and VarLong sizes + return VARLONG_EXACT_BYTE_LENGTHS[Long.numberOfLeadingZeros(data)]; + } + private static final int[] VARLONG_EXACT_BYTE_LENGTHS = new int[65]; + static { + for (int i = 0; i < 64; ++i) { + VARLONG_EXACT_BYTE_LENGTHS[i] = (int) Math.ceil((63d - (i - 1)) / 7d); + } + VARLONG_EXACT_BYTE_LENGTHS[64] = 1; // Special case for the number 0 + } + static int getByteSizeOld(long data) { // public -> package-private + // Gale end - Velocity - pre-compute VarInt and VarLong sizes for (int i = 1; i < 10; i++) { if ((data & -1L << i * 7) == 0L) { return i;