Skip to content

Commit ab45b9e

Browse files
committed
perf: improve setSequences() performance
Signed-off-by: Jack Cherng <jfcherng@gmail.com>
1 parent b4b20fb commit ab45b9e

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

src/SequenceMatcher.php

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,12 +169,32 @@ public function resetCachedResults(): self
169169
/**
170170
* Set the first and second sequences to use with the sequence matcher.
171171
*
172+
* This method is more effecient than "->setSeq1($old)->setSeq2($new)"
173+
* because it only run the routine once.
174+
*
172175
* @param string[] $a an array containing the lines to compare against
173176
* @param string[] $b an array containing the lines to compare
174177
*/
175178
public function setSequences(array $a, array $b): self
176179
{
177-
return $this->setSeq1($a)->setSeq2($b);
180+
$need_routine = false;
181+
182+
if ($this->a !== $a) {
183+
$need_routine = true;
184+
$this->a = $a;
185+
}
186+
187+
if ($this->b !== $b) {
188+
$need_routine = true;
189+
$this->b = $b;
190+
}
191+
192+
if ($need_routine) {
193+
$this->chainB();
194+
$this->resetCachedResults();
195+
}
196+
197+
return $this;
178198
}
179199

180200
/**
@@ -699,3 +719,15 @@ private function isBJunk(string $b): bool
699719
return isset($this->junkDict[$b]);
700720
}
701721
}
722+
723+
$sm = new SequenceMatcher([], []);
724+
$old = ['a'];
725+
$new = ['a', 'b', 'c'];
726+
727+
$sm->setSeq1($old)->setSeq2($new);
728+
729+
$old = ['a', 'b'];
730+
$new = ['a', 'b', 'c'];
731+
732+
$sm->setSeq1($old)->setSeq2($new);
733+
$sm->getOpcodes();

0 commit comments

Comments
 (0)