Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variables in inline function

Tags:

c++

static

inline

I have a hash function defined in a header file which I want to make sure is being inlined, but it uses a very large const static buffer of ints. I am wondering whether this buffer will affect the ability of the function to be inlined. Here is the code,(it's based on a crc32 implementation found here).

inline HashId hash(const void *value, const size_t length,
   const HashId previous = 0)
{
   // Here is the really large const static buffer.
   static const unsigned int crcTable[256] = { /* 256 Unique ints */ };

   // Short hash calculation
   unsigned char *cast = (unsigned char*) value;
   unsigned int crc32 = previous ^ 0xFFFFFFFF;
   for (size_t i = 0; i < length; ++i)
   {
      crc32 = (crc32 >> 8) ^ crcTable[ (crc32 ^ cast[i]) & 0xFF];
   }
   return (crc32 ^ 0xFFFFFFFF);
}

My hope is, that if the input is known at compile time, then this call will get compiled away into a single value. Is this expecting too much of the compiler? I'm compiling with gcc 4.6 with -O2, but I'm also interested to hear how other compilers might treat this.

like image 376
Darcy Rayner Avatar asked Sep 09 '26 23:09

Darcy Rayner


1 Answers

As Oli indicates, your best bet is to simply look at the compiler output. However, here are some things to consider:

  • If the contents of the static are truly constant you will be better putting this in an anonymous namespace. This ensures its initialization has nothing to do with calling the function.
  • type of the static. Your example is quite trivial and thus will probably be fine, but other types will be different. Note that the initialization of such statics may or must be deferred until the block is entered (puzzle through the standard at 6.7 if you want)
  • Multi-threading, relating to the previous this initialization may be required to use a mutex to prevent multiple threads from doing the initialization.

Given the possible scenarios it'd be best to not have statics inside your function if you wish it to be inlined. But each compiler is different, and all types are not equal.

Whether the compiler can actually reduce this function to a compile-time constant is just an extended issue to whether it can inline the static at all. You may also wish to look at constexpr specifier if you can use C++11.

like image 90
edA-qa mort-ora-y Avatar answered Sep 12 '26 13:09

edA-qa mort-ora-y



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!