Skip to content

Commit 36c1dbf

Browse files
committed
Improve performance of CompoundTag->equals() and ListTag->equals()
1 parent 53db374 commit 36c1dbf

File tree

2 files changed

+10
-6
lines changed

2 files changed

+10
-6
lines changed

src/tag/CompoundTag.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -347,12 +347,12 @@ public function getIterator() : \Generator{
347347
}
348348

349349
public function equals(Tag $that) : bool{
350-
if(!($that instanceof $this) or $this->count() !== $that->count()){
350+
if(!($that instanceof $this) or count($this->value) !== count($that->value)){
351351
return false;
352352
}
353353

354-
foreach($this as $k => $v){
355-
$other = $that->getTag($k);
354+
foreach($this->value as $k => $v){
355+
$other = $that->value[$k] ?? null;
356356
if($other === null or !$v->equals($other)){
357357
return false;
358358
}

src/tag/ListTag.php

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@
2828
use pocketmine\nbt\NbtStreamReader;
2929
use pocketmine\nbt\NbtStreamWriter;
3030
use pocketmine\nbt\ReaderTracker;
31+
use function assert;
32+
use function count;
3133
use function func_num_args;
3234
use function get_class;
3335
use function iterator_to_array;
@@ -304,12 +306,14 @@ public function getIterator() : \Generator{
304306
}
305307

306308
public function equals(Tag $that) : bool{
307-
if(!($that instanceof $this) or $this->count() !== $that->count()){
309+
if(!($that instanceof $this) or count($this->value) !== count($that->value)){
308310
return false;
309311
}
310312

311-
foreach($this as $k => $v){
312-
if(!$v->equals($that->get($k))){
313+
$thatValues = $that->getValue(); //SplDoublyLinkedList has O(n) random access, so this is faster than repeated get() calls
314+
foreach($this->value as $k => $v){
315+
assert(isset($thatValues[$k]), "We checked the count above, so this should not be missing");
316+
if(!$v->equals($thatValues[$k])){
313317
return false;
314318
}
315319
}

0 commit comments

Comments
 (0)