Skip to content

Commit 8182c29

Browse files
authored
Merge pull request #6 from Toflar/fix-multiple-instances
Performance improvement when using multiple instances
2 parents f12bbfb + da6ea31 commit 8182c29

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

src/LanguageData.php

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ class LanguageData extends LanguageSubset
2929
/** @var bool $isSubset */
3030
protected $isSubset;
3131

32+
private static array $fileContents = [];
33+
3234
public function __construct(?string $ngramsFile = null)
3335
{
3436
// Opcache needs to be active, so the load of the database array does not add overhead.
@@ -38,7 +40,7 @@ public function __construct(?string $ngramsFile = null)
3840
if ($ngramsFile && !file_exists($folder . $file)) {
3941
$folder .= 'subset/';
4042
}
41-
$ngramsData = include $folder . $file;
43+
$ngramsData = $this->loadFileContents($folder . $file);
4244
if (empty($ngramsData['ngrams']) || empty($ngramsData['languages'])) {
4345
throw new RuntimeException(sprintf('File "%s" data is invalid', $file));
4446
}
@@ -49,7 +51,21 @@ public function __construct(?string $ngramsFile = null)
4951
/** @var int $maxLang Highest language index key */
5052
$maxLang = max(array_keys($this->langCodes));
5153
$this->langScore = array_fill(0, $maxLang + 1, 0.0);
52-
$this->avgScore = include __DIR__ . '/../resources/avgScore.php';
54+
$this->avgScore = $this->loadFileContents(__DIR__ . '/../resources/avgScore.php');
55+
}
56+
57+
/**
58+
* Prevent including the same file multiple times
59+
*/
60+
private function loadFileContents(string $file): array
61+
{
62+
if (isset(self::$fileContents[$file])) {
63+
return self::$fileContents[$file];
64+
}
65+
66+
$data = require_once $file;
67+
68+
return self::$fileContents[$file] = $data;
5369
}
5470

5571
/*

0 commit comments

Comments
 (0)