BaseInventory: improved performance of getContents()

this old code is extremely inefficient. This showed up distinctly in my crafting bruteforce benchmarks, where I discovered that getContents() accounted for the vast majority of the time taken to match shaped recipes.
This commit is contained in:
Dylan K. Taylor 2018-03-27 10:13:28 +01:00
parent c7e803372c
commit 7e20385bdb

View File

@ -99,10 +99,13 @@ abstract class BaseInventory implements Inventory{
*/
public function getContents(bool $includeEmpty = false) : array{
$contents = [];
for($i = 0, $size = $this->getSize(); $i < $size; ++$i){
$item = $this->getItem($i);
if($includeEmpty or !$item->isNull()){
$contents[$i] = $item;
$air = null;
foreach($this->slots as $i => $slot){
if($slot !== null){
$contents[$i] = clone $slot;
}elseif($includeEmpty){
$contents[$i] = $air ?? ($air = ItemFactory::get(Item::AIR, 0, 0));
}
}