Index: trac/versioncontrol/cache.py
===================================================================
--- trac/versioncontrol/cache.py	(revision 6814)
+++ trac/versioncontrol/cache.py	(working copy)
@@ -236,8 +236,37 @@
         return self.repos.previous_rev(rev)
 
     def next_rev(self, rev, path=''):
-        return self.repos.next_rev(rev, path)
+        # My guess at the #5213 slowness is caused by the bad running time of
+        # the underlying repos.next_rev, so utilize the cached representation
+        # instead for WAY better performance.
 
+        query = "SELECT rev FROM node_change WHERE " + \
+                self.db.cast('rev', 'int') + " > %s"
+        args = [rev]
+
+        if path:
+            # Child changes
+            query += " AND (path %s OR " % self.db.like()
+            args.append(self.db.like_escape(path.lstrip('/')) + '%')
+            # Parent deletion
+            components = path.lstrip('/').split('/')
+            for i in range(1, len(components)+1):
+                args.append('/'.join(components[:i]))
+            parent_insert = ','.join(('%s',) * len(components))
+            query += " (path in (" + parent_insert + ") and change_type='D')"
+            query += ")"
+
+        query += " ORDER BY " + self.db.cast('rev', 'int') + \
+                 " LIMIT 1"
+        
+        cursor = self.db.cursor()
+        cursor.execute(query, args)
+        row = cursor.fetchone()
+        if not row:
+            return None
+        else:
+            return row[0]
+
     def rev_older_than(self, rev1, rev2):
         return self.repos.rev_older_than(rev1, rev2)
 