diff --git a/benchmark/https/https-session-cache.js b/benchmark/https/https-session-cache.js new file mode 100644 index 00000000000000..10cb9b171ff686 --- /dev/null +++ b/benchmark/https/https-session-cache.js @@ -0,0 +1,43 @@ +'use strict'; + +const common = require('../common.js'); +const https = require('https'); +const crypto = require('crypto'); + +const bench = common.createBenchmark(main, { + n: [100, 1000, 10000], + sessions: [10, 100, 256], +}); + +function generateSessionId() { + return crypto.randomBytes(32).toString('hex'); +} + +function main({ n, sessions }) { + const agent = new https.Agent({ + maxCachedSessions: sessions, + }); + + // Create dummy session objects + const sessionData = Buffer.allocUnsafe(1024); + + bench.start(); + + for (let i = 0; i < n; i++) { + // Simulate session caching operations + const sessionId = `session-${i % sessions}`; + + // Cache session + agent._cacheSession(sessionId, sessionData); + + // Occasionally evict sessions + if (i % 10 === 0) { + agent._evictSession(`session-${Math.floor(Math.random() * sessions)}`); + } + + // Get session + agent._getSession(sessionId); + } + + bench.end(n); +} \ No newline at end of file diff --git a/lib/https.js b/lib/https.js index fd9ae36e7b4d6f..8ed3be571858fe 100644 --- a/lib/https.js +++ b/lib/https.js @@ -572,29 +572,34 @@ Agent.prototype._cacheSession = function _cacheSession(key, session) { if (this.maxCachedSessions === 0) return; + // Cache property accesses for better performance + const map = this._sessionCache.map; + // Fast case - update existing entry - if (this._sessionCache.map[key]) { - this._sessionCache.map[key] = session; + if (map[key]) { + map[key] = session; return; } // Put new entry - if (this._sessionCache.list.length >= this.maxCachedSessions) { - const oldKey = ArrayPrototypeShift(this._sessionCache.list); + const list = this._sessionCache.list; + if (list.length >= this.maxCachedSessions) { + const oldKey = ArrayPrototypeShift(list); debug('evicting %j', oldKey); - delete this._sessionCache.map[oldKey]; + delete map[oldKey]; } - ArrayPrototypePush(this._sessionCache.list, key); - this._sessionCache.map[key] = session; + ArrayPrototypePush(list, key); + map[key] = session; }; Agent.prototype._evictSession = function _evictSession(key) { - const index = ArrayPrototypeIndexOf(this._sessionCache.list, key); + const list = this._sessionCache.list; + const index = ArrayPrototypeIndexOf(list, key); if (index === -1) return; - ArrayPrototypeSplice(this._sessionCache.list, index, 1); + ArrayPrototypeSplice(list, index, 1); delete this._sessionCache.map[key]; };