Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(lru): don't clear an already cached key on set #725

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions internal/lrucache.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ class LRUCache {
}

set (key, value) {
const deleted = this.delete(key)
this.delete(key)

Comment on lines +24 to 25
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
this.delete(key)

Copy link
Contributor Author

@jviide jviide Jul 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removing the this.delete(key) would turn the LRU cache implementation into a mixture of LRU and FIFO caches. It may not be relevant with the module's current usage pattern. However, it could lead to a surprise down the road if the cache module's usage is expanded.

I suggest either keeping the delete call, removing the delete while calling the cache implementation something else than an LRU, or just closing this pull request as unnecessary (as it does not affect currently observable behavior like you pointed out). I ran the benchmarks and removing or keeping the delete call seems to make no difference there, though there are currently no benchmarks that heavily exercise the .set method.

if (!deleted && value !== undefined) {
if (value !== undefined) {
// If cache is full, delete the least recently used item
if (this.map.size >= this.max) {
const firstKey = this.map.keys().next().value
Expand Down
22 changes: 22 additions & 0 deletions test/internal/lrucache.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,25 @@ test('basic cache operation', t => {
c.set(42, undefined)
t.end()
})

test('test setting the same key twice', t => {
const c = new LRUCache()
c.set(1, 1)
c.set(1, 2)
t.equal(c.get(1), 2)
t.end()
})

test('test that setting an already cached key bumps it last in the LRU queue', t => {
const c = new LRUCache()
const max = 1000

for (let i = 0; i < max; i++) {
c.set(i, i)
}
c.set(0, 0)
c.set(1001, 1001)
t.equal(c.get(0), 0)
t.equal(c.get(1), undefined)
t.end()
})
Loading