From 51795ccbd1347ac9ad0f28e2a537c4b8186c3253 Mon Sep 17 00:00:00 2001 From: themode Date: Fri, 7 Jan 2022 01:35:43 +0100 Subject: [PATCH] Avoid second map operation --- .../server/instance/palette/PaletteImpl.java | 12 ++++++------ .../net/minestom/server/instance/PaletteTest.java | 7 +++++++ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/main/java/net/minestom/server/instance/palette/PaletteImpl.java b/src/main/java/net/minestom/server/instance/palette/PaletteImpl.java index 88be64f50..282a43be3 100644 --- a/src/main/java/net/minestom/server/instance/palette/PaletteImpl.java +++ b/src/main/java/net/minestom/server/instance/palette/PaletteImpl.java @@ -61,6 +61,7 @@ final class PaletteImpl implements Palette, Cloneable { this.paletteToValueList.add(0); this.valueToPaletteMap = new Int2IntOpenHashMap(1); this.valueToPaletteMap.put(0, 0); + this.valueToPaletteMap.defaultReturnValue(-1); } @Override @@ -362,18 +363,17 @@ final class PaletteImpl implements Palette, Cloneable { private int getPaletteIndex(int value) { if (!hasPalette) return value; - final int lookup = valueToPaletteMap.getOrDefault(value, (short) -1); - if (lookup != -1) return lookup; - + final int lastPaletteIndex = this.lastPaletteIndex; if (lastPaletteIndex >= maxPaletteSize(bitsPerEntry)) { // Palette is full, must resize resize(bitsPerEntry + bitsIncrement); return getPaletteIndex(value); } - final int paletteIndex = lastPaletteIndex++; + final int lookup = valueToPaletteMap.putIfAbsent(value, lastPaletteIndex); + if (lookup != -1) return lookup; + this.lastPaletteIndex = lastPaletteIndex + 1; this.paletteToValueList.add(value); - this.valueToPaletteMap.put(value, paletteIndex); - return paletteIndex; + return lastPaletteIndex; } int getSectionIndex(int x, int y, int z) { diff --git a/src/test/java/net/minestom/server/instance/PaletteTest.java b/src/test/java/net/minestom/server/instance/PaletteTest.java index 7312b2a4d..8edfe9b65 100644 --- a/src/test/java/net/minestom/server/instance/PaletteTest.java +++ b/src/test/java/net/minestom/server/instance/PaletteTest.java @@ -14,6 +14,13 @@ import static org.junit.jupiter.api.Assertions.*; public class PaletteTest { + @Test + public void singlePlacement() { + var palette = Palette.blocks(); + palette.set(0, 0, 1, 1); + assertEquals(1, palette.get(0, 0, 1)); + } + @Test public void placement() { var palettes = testPalettes();