Caching creative inventory entries (#5703)

Due to the high cost of Item::serializeCompoundTag(), it's very costly to rebuild this every time we need it. This is sent during the pre-spawn step, where we need to minimize costs as much as possible.
This commit is contained in:
ShockedPlot7560
2023-05-18 15:11:28 +02:00
committed by GitHub
parent 0547383296
commit db95bf8b9b
3 changed files with 93 additions and 13 deletions

View File

@ -25,7 +25,9 @@ namespace pocketmine\inventory;
use pocketmine\item\Durable;
use pocketmine\item\Item;
use pocketmine\utils\DestructorCallbackTrait;
use pocketmine\utils\Filesystem;
use pocketmine\utils\ObjectSet;
use pocketmine\utils\SingletonTrait;
use pocketmine\utils\Utils;
use Symfony\Component\Filesystem\Path;
@ -33,11 +35,17 @@ use function json_decode;
final class CreativeInventory{
use SingletonTrait;
use DestructorCallbackTrait;
/** @var Item[] */
private array $creative = [];
/** @phpstan-var ObjectSet<\Closure() : void> */
private ObjectSet $contentChangedCallbacks;
private function __construct(){
$this->contentChangedCallbacks = new ObjectSet();
$creativeItems = json_decode(Filesystem::fileGetContents(Path::join(\pocketmine\RESOURCE_PATH, "legacy_creativeitems.json")), true);
foreach($creativeItems as $data){
@ -55,6 +63,7 @@ final class CreativeInventory{
*/
public function clear() : void{
$this->creative = [];
$this->onContentChange();
}
/**
@ -84,6 +93,7 @@ final class CreativeInventory{
*/
public function add(Item $item) : void{
$this->creative[] = clone $item;
$this->onContentChange();
}
/**
@ -94,10 +104,22 @@ final class CreativeInventory{
$index = $this->getItemIndex($item);
if($index !== -1){
unset($this->creative[$index]);
$this->onContentChange();
}
}
public function contains(Item $item) : bool{
return $this->getItemIndex($item) !== -1;
}
/** @phpstan-return ObjectSet<\Closure() : void> */
public function getContentChangedCallbacks() : ObjectSet{
return $this->contentChangedCallbacks;
}
private function onContentChange() : void{
foreach($this->contentChangedCallbacks as $callback){
$callback();
}
}
}