3 ms·
>...clone the pure function's result as needed instead of calling it multiple times It is reasonably easy to do a caching function that takes arbitrary functio
by Akronymus 6y ago
>...clone the pure function's result as needed instead of calling it multiple times
It is reasonably easy to do a caching function that takes arbitrary functions and data and caches their result as a map of tuples (data, function, timestamp for example). Definitely not always the right thing to do, but could eek out some performance in where you get the same data multiple times.
Edit: I found that it is called memoization: Looks to me to very easily be extensible to allow timestamps too, to check if the record is older than X.
https://stackoverflow.com/questions/833180/handy-f-snippets/851449#851449 https://stackoverflow.com/questions/833180/handy-f-snippets/...
- brundolf 6y agoYes, but: > unless you expect them to be mutated by other code down the line and are guarding against side-effects Sometimes you hand off a mutable object to some other code and that code mutates it for its own purposes. If you hand the same object to multiple functions in this case, they'll all see each other's changes and if this wasn't intentional then voila, you've got a bug. This is one motivation for immutable data structures: you don't have to worry about whether an object might get mutated so you don't have to eagerly clone it. But in an existing codebase it may not be a trivial thing to simply introduce immutability. This is why, instead, I suggested making that defensive cloning explicit and decoupled from the rest of the logic.
- Akronymus 6y agoIn that case, you could adjust the memoize function to return a copy. Altough that would lead to other problems such as shallow or deep copy and such.