Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC function attributes vs caching

I have one costly function that gets called many times and there is a very limited set of possible values for the parameter.
Function return code depends only on arguments so the obvious way to speed things up is to keep a static cache within the function for possible arguments and corresponding return codes, so for every combination of the parameters, the costly operation will be performed only once.
I always use this approach in such situations and it works fine but it just occurred to me that GCC function attributes const or pure probably can help me with this.

Does anybody have experience with this? How GCC uses pure and const attributes - only at compile time or at runtime as well?
Can I rely on GCC to be smart enough to call a function, declared as

int foo(int) __attribute__ ((pure))

just once for the same parameter value, or there is no guarantee whatsoever and I better stick to caching approach?

EDIT: My question is not about caching/memoization/lookup tables, but GCC function atributes.

like image 577
qrdl Avatar asked Mar 09 '26 15:03

qrdl


1 Answers

I think you are confusing the GCC pure attribute with memoization.

The GCC pure attribute allows the compiler to reduce the number of times the function is called in certain circumstances (such as loop unrolling). However it makes no guarantees that it will do so, only if it think it's appropriate.

What you appear to be looking for is memoization of your function. Memoization is an optimization where calculations for the same input should not be repeated. Instead the previous result should be returned. The GCC pure attribute does not make a function work in this way. You would have to hand implement this.

like image 158
JaredPar Avatar answered Mar 12 '26 06:03

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!