@@ -177,29 +177,42 @@ private void processSellResult(Player player, SpawnerData spawner, SellResult se
177177 /**
178178 * Calculates the total sell value of items using cached accumulated value
179179 * This method is optimized to use pre-calculated sell values
180+ * OPTIMIZED: Single-pass iteration with progressive capacity adjustment
180181 */
181182 private SellResult calculateSellValue (Map <VirtualInventory .ItemSignature , Long > consolidatedItems ,
182183 SpawnerData spawner ) {
183184 // Use the accumulated sell value from spawner (already calculated incrementally)
184185 double totalValue = spawner .getAccumulatedSellValue ();
185186 long totalItemsSold = 0 ;
186- List <ItemStack > itemsToRemove = new ArrayList <>();
187187
188- // We still need to create the items list for removal
188+ // Start with reasonable initial capacity (will grow progressively)
189+ // Use ArrayList directly to access ensureCapacity method
190+ ArrayList <ItemStack > itemsToRemove = new ArrayList <>();
191+
192+ // Single-pass iteration: calculate stacks needed AND create them
189193 for (Map .Entry <VirtualInventory .ItemSignature , Long > entry : consolidatedItems .entrySet ()) {
190- ItemStack template = entry .getKey ().getTemplate ();
194+ // Use getTemplateRef() to avoid cloning when reading properties
195+ ItemStack templateRef = entry .getKey ().getTemplateRef ();
191196 long amount = entry .getValue ();
192-
193- // Count items (we need this even if we skip price calculation)
197+ int maxStackSize = templateRef .getMaxStackSize ();
198+
199+ // Count items for statistics
194200 totalItemsSold += amount ;
195201
202+ // Calculate how many stacks this item type needs
203+ int stacksNeeded = (int ) Math .ceil ((double ) amount / maxStackSize );
204+
205+ // Ensure capacity before adding to avoid resizing during loop
206+ // This is cheaper than multiple resizes
207+ itemsToRemove .ensureCapacity (itemsToRemove .size () + stacksNeeded );
208+
196209 // Create ItemStacks to remove (handle stacking properly)
197210 long remainingAmount = amount ;
198211 while (remainingAmount > 0 ) {
199- ItemStack stackToRemove = template .clone ();
200- int stackSize = (int ) Math .min (remainingAmount , template . getMaxStackSize () );
212+ ItemStack stackToRemove = templateRef .clone (); // Single clone per stack
213+ int stackSize = (int ) Math .min (remainingAmount , maxStackSize );
201214 stackToRemove .setAmount (stackSize );
202- itemsToRemove .add (stackToRemove );
215+ itemsToRemove .add (stackToRemove ); // No resize thanks to ensureCapacity
203216 remainingAmount -= stackSize ;
204217 }
205218 }
0 commit comments