What’s the most efficient way to build a cache with arbitrary Ruby objects as keys that are expired based on a least recently used algorithm. It should use Ruby’s normal hashing semantics (not equal?)
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This pushes the boundaries of my understanding of how Ruby uses memory, but I suspect that the most efficient implementation would be a doubly-linked list where every access moves the key to the front of the list, and every insert drops an item if the maximum size has been reached.
However, assuming Ruby’s
Hashclass is already very efficient, I’d bet that the somewhat naive solution of simply adding age data to aHashwould be fairly good. Here’s a quick toy example that does this:There’s probably a faster way of finding the oldest item, and this is not thoroughly tested, but I’d be curious to know how anyone thinks this compares to a more sophisticated design, linked list or otherwise.