diff --git a/src/MenuTrailByPathActiveTrail.php b/src/MenuTrailByPathActiveTrail.php
index cd154d0..83fdd80 100644
--- a/src/MenuTrailByPathActiveTrail.php
+++ b/src/MenuTrailByPathActiveTrail.php
@@ -39,6 +39,7 @@ class MenuTrailByPathActiveTrail extends MenuActiveTrail {
 
   /**
    * MenuTrailByPathActiveTrail constructor.
+   *
    * @param \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager
    * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
    * @param \Drupal\Core\Cache\CacheBackendInterface $cache
@@ -75,7 +76,7 @@ class MenuTrailByPathActiveTrail extends MenuActiveTrail {
   protected function doGetActiveTrailIds($menu_name) {
     // Parent ids; used both as key and value to ensure uniqueness.
     // We always want all the top-level links with parent == ''.
-    $active_trail = array('' => '');
+    $active_trail = ['' => ''];
 
     // If a link in the given menu indeed matches the path, then use it to
     // complete the active trail.
@@ -94,18 +95,32 @@ class MenuTrailByPathActiveTrail extends MenuActiveTrail {
    * @param string $menu_name
    *   The menu within which to find the active trail link.
    *
-   * @return \Drupal\Core\Menu\MenuLinkInterface|NULL
+   * @return \Drupal\Core\Menu\MenuLinkInterface|null
    *   The menu link for the given menu, or NULL if there is no matching menu link.
    */
   public function getActiveTrailLink($menu_name) {
     $menu_links = $this->menuHelper->getMenuLinks($menu_name);
     $trail_urls = $this->pathHelper->getUrls();
 
-    foreach (array_reverse($trail_urls) as $trail_url) {
-      foreach (array_reverse($menu_links) as $menu_link) {
-        /* @var $menu_link \Drupal\Core\Menu\MenuLinkInterface */
-        /* @var $trail_url \Drupal\Core\Url */
-        if ($menu_link->getUrlObject()->toString() == $trail_url->toString()) {
+    // Gather menu urls strings.
+    $menu_url_strings = [];
+    foreach ($menu_links as $menu_link) {
+      /* @var $menu_link \Drupal\Core\Menu\MenuLinkInterface */
+      $menu_url_strings[$menu_link->getUrlObject()->toString()] = $menu_link;
+    }
+
+    // Gather trail urls strings.
+    $trail_url_strings = [];
+    foreach ($trail_urls as $trail_url) {
+      /* @var $trail_url \Drupal\Core\Url */
+      $trail_url_strings[] = $trail_url->toString();
+    }
+
+    // Loop over the gather trail & menu url strings.
+    foreach (array_reverse($trail_url_strings) as $trail_url_string) {
+      foreach (array_reverse($menu_url_strings) as $menu_url_string => $menu_link) {
+        if ($menu_url_string == $trail_url_string) {
+          /* @var $menu_link \Drupal\Core\Menu\MenuLinkInterface */
           return $menu_link;
         }
       }
@@ -113,4 +128,5 @@ class MenuTrailByPathActiveTrail extends MenuActiveTrail {
 
     return NULL;
   }
+
 }
