I have implemented a fast comparison function which uses a look-up table. Since this function is used in multiple classes in the project, I need to make sure that there is only one copy of the look-up table during the whole execution of the program.
The look-up table is a simple vector<int>
of size 65536. I wish that this table is initialized at the beginning of the program, not at the time of its first use. How to deal with this problem?
The following code snippet is the current version of my comparison function. I believe that by making lookup_table
a static variable, the problem will be resolved only partially, because the lifetime of static variables begins the first time the program flow encounters the declaration.
int fast_compare(const char* array1, const char* array2, int length)
{
static const vector<int> lookup_table = init_lookup_table();
// process the input arrays...
// ...
return lookup_table[...];
}
vector<int> init_lookup_table()
{
vector<int> lut(65536);
// ----------------------------
// initialize the look-up table
// ...
// ...
// end of initialization
// ----------------------------
return lut;
}