Reputation: 3455
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.
Upvotes: 3
Views: 2939
Reputation: 31951
As Oli indicates, your best bet is to simply look at the compiler output. However, here are some things to consider:
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.
Upvotes: 2