Skip to content

Commit a1447ba

Browse files
authored
perf: optimize entries, keys, and values methods (#386)
* perf: optimize entries, keys, and values methods * fix: change LRUCache to LRUCacheWithDelete import
1 parent cfd2f89 commit a1447ba

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

benchmarks/comparison-benchmark.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ try {
3030
try {
3131
// Import from mnemonist using the correct export pattern
3232
const mnemonistModule = await import("mnemonist");
33-
MnemonistLRU = mnemonistModule.LRUCache;
33+
MnemonistLRU = mnemonistModule.LRUCacheWithDelete;
3434
} catch (error) {
3535
console.error("mnemonist not found. Run: npm install --no-save mnemonist");
3636
console.error("Error:", error.message);

src/lru.js

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,13 @@ export class LRU {
119119
* @since 11.1.0
120120
*/
121121
entries (keys = this.keys()) {
122-
return keys.map(key => [key, this.get(key)]);
122+
const result = new Array(keys.length);
123+
for (let i = 0; i < keys.length; i++) {
124+
const key = keys[i];
125+
result[i] = [key, this.get(key)];
126+
}
127+
128+
return result;
123129
}
124130

125131
/**
@@ -296,11 +302,12 @@ export class LRU {
296302
* @since 9.0.0
297303
*/
298304
keys () {
299-
const result = [];
305+
const result = new Array(this.size);
300306
let x = this.first;
307+
let i = 0;
301308

302309
while (x !== null) {
303-
result.push(x.key);
310+
result[i++] = x.key;
304311
x = x.next;
305312
}
306313

@@ -429,7 +436,12 @@ export class LRU {
429436
* @since 11.1.0
430437
*/
431438
values (keys = this.keys()) {
432-
return keys.map(key => this.get(key));
439+
const result = new Array(keys.length);
440+
for (let i = 0; i < keys.length; i++) {
441+
result[i] = this.get(keys[i]);
442+
}
443+
444+
return result;
433445
}
434446
}
435447

0 commit comments

Comments
 (0)