From f517b294d5c7ceb4a244c882538762dc9ce8cefb Mon Sep 17 00:00:00 2001
From: TheMode <themode@outlook.fr>
Date: Sat, 6 Nov 2021 06:44:35 +0100
Subject: [PATCH] Optimize section write, use a basic hashmap

Signed-off-by: TheMode <themode@outlook.fr>
---
 .../server/instance/DynamicChunk.java         | 23 +++++++++++++------
 1 file changed, 16 insertions(+), 7 deletions(-)

diff --git a/src/main/java/net/minestom/server/instance/DynamicChunk.java b/src/main/java/net/minestom/server/instance/DynamicChunk.java
index 199c713cd..dd51e1a3f 100644
--- a/src/main/java/net/minestom/server/instance/DynamicChunk.java
+++ b/src/main/java/net/minestom/server/instance/DynamicChunk.java
@@ -1,7 +1,7 @@
 package net.minestom.server.instance;
 
 import com.extollit.gaming.ai.path.model.ColumnarOcclusionFieldList;
-import it.unimi.dsi.fastutil.ints.Int2ObjectAVLTreeMap;
+import it.unimi.dsi.fastutil.ints.Int2ObjectMaps;
 import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
 import net.minestom.server.coordinate.Point;
 import net.minestom.server.entity.Player;
@@ -32,7 +32,7 @@ import java.util.*;
  */
 public class DynamicChunk extends Chunk {
 
-    protected final Int2ObjectAVLTreeMap<Section> sectionMap = new Int2ObjectAVLTreeMap<>();
+    protected final Int2ObjectOpenHashMap<Section> sectionMap = new Int2ObjectOpenHashMap<>();
 
     // Key = ChunkUtils#getBlockIndex
     protected final Int2ObjectOpenHashMap<Block> entries = new Int2ObjectOpenHashMap<>();
@@ -174,11 +174,20 @@ public class DynamicChunk extends Chunk {
         // Data
         final BinaryWriter writer = new BinaryWriter();
         for (int i = 0; i < 16; i++) { // TODO: variable section count
-            final Section section = Objects.requireNonNullElseGet(sectionMap.get(i), Section::new);
-            final Palette blockPalette = section.blockPalette();
-            writer.writeShort((short) blockPalette.size());
-            blockPalette.write(writer); // Blocks
-            section.biomePalette().write(writer); // Biomes
+            final Section section = sectionMap.get(i);
+            if (section != null) {
+                final Palette blockPalette = section.blockPalette();
+                writer.writeShort((short) blockPalette.size());
+                blockPalette.write(writer); // Blocks
+                section.biomePalette().write(writer); // Biomes
+            } else {
+                // Hardcode empty section
+                writer.writeShort((short) 0); // Block count
+                writer.writeByte((byte) 15); // Block bpe
+                writer.writeVarInt(0); // Block data length
+                writer.writeByte((byte) 15); // Biome bpe
+                writer.writeVarInt(0); // Biome data length
+            }
         }
         return new ChunkDataPacket(chunkX, chunkZ,
                 new ChunkData(heightmapsNBT, writer.toByteArray(), entries),