From 68f6b7bb879c2c6d893da408a1336b0a604c70c8 Mon Sep 17 00:00:00 2001 From: Bradley Grainger Date: Tue, 24 Aug 2021 21:13:58 -0700 Subject: [PATCH] Make CreateKey faster. Use BinaryPrimitives instead of BinaryWriter to write directly to the array instead of via a MemoryStream. Move allocation of the key outside the loop to avoid creating unnecessary temporary objects. --- Maploader/World/World.cs | 16 +++++----------- PapyrusCs/PapyrusCs.csproj | 1 + 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/Maploader/World/World.cs b/Maploader/World/World.cs index 9a9ea0b..13c6744 100644 --- a/Maploader/World/World.cs +++ b/Maploader/World/World.cs @@ -1,4 +1,5 @@ using System; +using System.Buffers.Binary; using System.Collections; using System.Collections.Generic; using System.Diagnostics; @@ -460,16 +461,10 @@ private static (string, Dictionary) GetNbtVal(MemoryStream ms) private static byte[] CreateKey(int x, int z) { - // Todo: make it faster var key = new byte[10]; - using (var ms = new MemoryStream(key)) - using (var bs = new BinaryWriter(ms)) - { - bs.Write(x); - bs.Write(z); - bs.Write((byte) 47); - } - + BinaryPrimitives.WriteInt32LittleEndian(key.AsSpan(), x); + BinaryPrimitives.WriteInt32LittleEndian(key.AsSpan(4), z); + key[8] = 47; return key; } @@ -574,10 +569,9 @@ public ChunkData GetChunkData(int x, int z) Z = z, }; - + var key = CreateKey(x, z); foreach (var kvp in Enumerable.Range(0,15)) { - var key = CreateKey(x, z); key[9] = (byte)kvp; UIntPtr length; diff --git a/PapyrusCs/PapyrusCs.csproj b/PapyrusCs/PapyrusCs.csproj index 8110cf5..2b5b9a2 100644 --- a/PapyrusCs/PapyrusCs.csproj +++ b/PapyrusCs/PapyrusCs.csproj @@ -33,6 +33,7 @@ +