Skip to content

Implement selectLcsImplementation() #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 15, 2014
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 25 additions & 5 deletions src/Differ.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@

use SebastianBergmann\Diff\LCS\LongestCommonSubsequence;
use SebastianBergmann\Diff\LCS\TimeEfficientImplementation;
use SebastianBergmann\Diff\LCS\MemoryEfficientImplementation;

/**
* Diff implementation.
Expand Down Expand Up @@ -156,10 +157,6 @@ public function diff($from, $to, LongestCommonSubsequence $lcs = null)
*/
public function diffToArray($from, $to, LongestCommonSubsequence $lcs = null)
{
if ($lcs === null) {
$lcs = $this->selectLcsImplementation($from, $to);
}

preg_match_all('(\r\n|\r|\n)', $from, $fromMatches);
preg_match_all('(\r\n|\r|\n)', $to, $toMatches);

Expand Down Expand Up @@ -197,6 +194,10 @@ public function diffToArray($from, $to, LongestCommonSubsequence $lcs = null)
}
}

if ($lcs === null) {
$lcs = $this->selectLcsImplementation($from, $to);
}

$common = $lcs->calculate(array_values($from), array_values($to));
$diff = array();

Expand Down Expand Up @@ -252,7 +253,26 @@ public function diffToArray($from, $to, LongestCommonSubsequence $lcs = null)
*/
private function selectLcsImplementation($from, $to)
{
// @todo Automagically choose best strategy based on input size
// We don't want to use the time efficient implementation if it's memory
// footprint will probably exceed this value. Note that the footprint
// calculation is only an estimation for the matrix and the LCS method
// will typically allocate a bit more memory than this.
$memoryLimit = 100 * 1024*1024;
if ($this->calculateEstimatedFootprint($from, $to) > $memoryLimit) {
return new MemoryEfficientImplementation;
}
return new TimeEfficientImplementation;
}

/**
* Calculates the estimated memory footprint for the DP-based method.
*
* @param type $from
* @param type $to
*/
private function calculateEstimatedFootprint($from, $to)
{
$itemSize = PHP_INT_SIZE == 4 ? 76 : 144;
return $itemSize * pow(min(count($from), count($to)), 2);
}
}