jellydator / ttlcache

An in-memory cache with item expiration and generics
MIT License
930 stars 116 forks source link

Added ModifyOrSetFunc #112

Closed owen5mith closed 11 months ago

owen5mith commented 1 year ago

Hello,

This PR adds a ModifyOrSetFunc method to the cache. The main motivation for this was to avoid allocations when using the cache to store slices as well as to have an atomic way of creating or updating these slices. ModifyOrSetFunc takes two function arguments, one that is called if a key already exists, and it's return value is used to update the key's value.

The second function is called if the key does not exist, with it's return value being used as the key's value. By using a function for the Set value, over simply passing the value in, such as in GetOrSet, you avoid any allocations if the key is already present, which when being used with large values such as make([]int, 0, 10000), provides a significant speedup as well as reduced GC load.

I'm conscious I don't have a corresponding issue for this, so feel free to decline if this isn't something you think should be part of this library. I did see https://github.com/jellydator/ttlcache/issues/72 which feels loosely related.

swithek commented 11 months ago

Though I understand why this might be needed in some cases, I'm not sure whether it should be added to the library. Perhaps, as you said, we should focus on the transaction feature first?