Browse Source

Merge pull request #8438 from MichaelThessel/master

Improve hasPackage() performance
Jordi Boggiano 5 years ago
parent
commit
0f7a64839e
1 changed files with 16 additions and 6 deletions
  1. 16 6
      src/Composer/Repository/ArrayRepository.php

+ 16 - 6
src/Composer/Repository/ArrayRepository.php

@@ -28,6 +28,11 @@ class ArrayRepository extends BaseRepository
 {
 {
     /** @var PackageInterface[] */
     /** @var PackageInterface[] */
     protected $packages;
     protected $packages;
+    
+    /** 
+      * @var PackageInterface[] indexed by package unique name and used to cache hasPackage calls
+      */
+    protected $packageMap;
 
 
     public function __construct(array $packages = array())
     public function __construct(array $packages = array())
     {
     {
@@ -121,15 +126,14 @@ class ArrayRepository extends BaseRepository
      */
      */
     public function hasPackage(PackageInterface $package)
     public function hasPackage(PackageInterface $package)
     {
     {
-        $packageId = $package->getUniqueName();
-
-        foreach ($this->getPackages() as $repoPackage) {
-            if ($packageId === $repoPackage->getUniqueName()) {
-                return true;
+        if ($this->packageMap === null) {
+            $this->packageMap = array();
+            foreach ($this->getPackages() as $repoPackage) {
+                $this->packageMap[$repoPackage->getUniqueName()] = $repoPackage;
             }
             }
         }
         }
 
 
-        return false;
+        return isset($this->packageMap[$package->getUniqueName()]);
     }
     }
 
 
     /**
     /**
@@ -151,6 +155,9 @@ class ArrayRepository extends BaseRepository
                 $this->addPackage($aliasedPackage);
                 $this->addPackage($aliasedPackage);
             }
             }
         }
         }
+
+        // invalidate package map cache
+        $this->packageMap = null;
     }
     }
 
 
     protected function createAliasPackage(PackageInterface $package, $alias, $prettyAlias)
     protected function createAliasPackage(PackageInterface $package, $alias, $prettyAlias)
@@ -171,6 +178,9 @@ class ArrayRepository extends BaseRepository
             if ($packageId === $repoPackage->getUniqueName()) {
             if ($packageId === $repoPackage->getUniqueName()) {
                 array_splice($this->packages, $key, 1);
                 array_splice($this->packages, $key, 1);
 
 
+                // invalidate package map cache
+                $this->packageMap = null;
+
                 return;
                 return;
             }
             }
         }
         }