When is it worth memoizing such a function (what if the computation was more intensive)?
It depends. Measure and profile, premature optimisation is the root of all evil.
Will the cpu ever optimize pure functions repeatedly called with the same arguments?
If the compiler can see that you have a pure function (no side effects, result only depends on arguments and no global/static state), then it may optimize repeated calls that are "near" each other (e.g. same function). C23 has attributes that help with that but C++ does not.
It's a function of some (atomic) state that very rarely changes.
If this function is only ever called at with one value at a time, then it might be easier to cache at callsite:
class holder { public: holder(float value) : value{ value } {} float get_value() const { return value; } void set_value(float value) { if (value != this->value) { this->value = value; cache.reset(); } } float get_calculation() const { if (!cache) { cache = expensive_calculation(value); } return *cache; } private: float value{}; // or just use non-mutable `float` // and always set in ctor and `set_value` mutable std::optional<float> cache{}; };
atomic. If you are doing this in multiple threads, then note that static variables are not themselves thread safe, just their initialization is. If not actual multithreading then no worries.