Skip to content

Commit 1534560

Browse files
Merge pull request sebastianbergmann#13 from mimrock/master
Implement selectLcsImplementation()
2 parents 2bbf893 + 5c5d2d2 commit 1534560

File tree

1 file changed

+25
-5
lines changed

1 file changed

+25
-5
lines changed

src/Differ.php

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646

4747
use SebastianBergmann\Diff\LCS\LongestCommonSubsequence;
4848
use SebastianBergmann\Diff\LCS\TimeEfficientImplementation;
49+
use SebastianBergmann\Diff\LCS\MemoryEfficientImplementation;
4950

5051
/**
5152
* Diff implementation.
@@ -156,10 +157,6 @@ public function diff($from, $to, LongestCommonSubsequence $lcs = null)
156157
*/
157158
public function diffToArray($from, $to, LongestCommonSubsequence $lcs = null)
158159
{
159-
if ($lcs === null) {
160-
$lcs = $this->selectLcsImplementation($from, $to);
161-
}
162-
163160
preg_match_all('(\r\n|\r|\n)', $from, $fromMatches);
164161
preg_match_all('(\r\n|\r|\n)', $to, $toMatches);
165162

@@ -197,6 +194,10 @@ public function diffToArray($from, $to, LongestCommonSubsequence $lcs = null)
197194
}
198195
}
199196

197+
if ($lcs === null) {
198+
$lcs = $this->selectLcsImplementation($from, $to);
199+
}
200+
200201
$common = $lcs->calculate(array_values($from), array_values($to));
201202
$diff = array();
202203

@@ -252,7 +253,26 @@ public function diffToArray($from, $to, LongestCommonSubsequence $lcs = null)
252253
*/
253254
private function selectLcsImplementation($from, $to)
254255
{
255-
// @todo Automagically choose best strategy based on input size
256+
// We don't want to use the time efficient implementation if it's memory
257+
// footprint will probably exceed this value. Note that the footprint
258+
// calculation is only an estimation for the matrix and the LCS method
259+
// will typically allocate a bit more memory than this.
260+
$memoryLimit = 100 * 1024*1024;
261+
if ($this->calculateEstimatedFootprint($from, $to) > $memoryLimit) {
262+
return new MemoryEfficientImplementation;
263+
}
256264
return new TimeEfficientImplementation;
257265
}
266+
267+
/**
268+
* Calculates the estimated memory footprint for the DP-based method.
269+
*
270+
* @param type $from
271+
* @param type $to
272+
*/
273+
private function calculateEstimatedFootprint($from, $to)
274+
{
275+
$itemSize = PHP_INT_SIZE == 4 ? 76 : 144;
276+
return $itemSize * pow(min(count($from), count($to)), 2);
277+
}
258278
}

0 commit comments

Comments
 (0)