From bfdf2dd8bf079bbee9f1405fee7bf4a83128e0bc Mon Sep 17 00:00:00 2001 From: Daniel Lockyer Date: Mon, 14 Oct 2024 17:01:51 +0200 Subject: [PATCH] Optimized loading dynamic redirects - the code kept an array of IDs, and would check new entries against the values of this array - this algorithm is O(n^2) and became quite slow when the site had a lot of redirects - we can do away with this entirely, and just compute the keys of the redirects to get the IDs - this speeds up loading redirects by 3x or so --- .../lib/DynamicRedirectManager.js | 10 +--------- .../test/DynamicRedirectManager.test.js | 1 - 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/ghost/express-dynamic-redirects/lib/DynamicRedirectManager.js b/ghost/express-dynamic-redirects/lib/DynamicRedirectManager.js index 9ec8d734e9..809b11f1de 100644 --- a/ghost/express-dynamic-redirects/lib/DynamicRedirectManager.js +++ b/ghost/express-dynamic-redirects/lib/DynamicRedirectManager.js @@ -16,8 +16,6 @@ class DynamicRedirectManager { /** @private */ this.router = express.Router(); - /** @private @type {string[]} */ - this.redirectIds = []; /** @private @type {Object.} */ this.redirects = {}; @@ -103,10 +101,6 @@ class DynamicRedirectManager { const fromRegex = this.buildRegex(from); const redirectId = from; - - if (!this.redirectIds.includes(redirectId)) { - this.redirectIds.push(redirectId); - } this.redirects[redirectId] = { fromRegex, @@ -131,11 +125,10 @@ class DynamicRedirectManager { * @returns {void} */ removeRedirect(redirectId) { - this.redirectIds.splice(this.redirectIds.indexOf(redirectId), 1); delete this.redirects[redirectId]; this.router = express.Router(); - this.redirectIds.forEach(id => this.setupRedirect(id)); + Object.keys(this.redirects).forEach(id => this.setupRedirect(id)); return; } @@ -144,7 +137,6 @@ class DynamicRedirectManager { * @returns {void} */ removeAllRedirects() { - this.redirectIds = []; this.redirects = {}; this.router = express.Router(); } diff --git a/ghost/express-dynamic-redirects/test/DynamicRedirectManager.test.js b/ghost/express-dynamic-redirects/test/DynamicRedirectManager.test.js index 1ad0ea06a8..f2e45a59c2 100644 --- a/ghost/express-dynamic-redirects/test/DynamicRedirectManager.test.js +++ b/ghost/express-dynamic-redirects/test/DynamicRedirectManager.test.js @@ -137,7 +137,6 @@ describe('DynamicRedirectManager', function () { req.url = '/redirect-me'; manager.removeAllRedirects(); - manager.redirectIds.should.be.empty(); manager.redirects.should.be.empty(); manager.handleRequest(req, res, function next() {