Real-World Examples of Metaprogramming II
Explore how to implement compile-time hash calculations in C++ to optimize runtime efficiency. This lesson shows you how to create a PrehashedString class, use constexpr functions, and verify the compiler generates hash sums at compile time for performance improvements.
Example 2: hash strings at compile time
Let’s say we have a resource system consisting of an unordered map of strings that identifies bitmaps. If a bitmap is already loaded, the system returns the loaded bitmap; otherwise, it loads the bitmap and returns it:
The bitmap cache is then utilized wherever a bitmap resource is needed:
- If it’s not loaded yet, the
get_bitmap_resource()function will load and return it - If it’s already been loaded somewhere else, the
get_bitmap_resource()will simply return the loaded function
So, independent of which of these draw functions is executed first, the second one will not have to load the bitmap from disk:
Since we use an unordered map, we must compute a hash value whenever we check for a bitmap resource. You will now see how we can optimize the runtime code by moving computations to compile time.
The advantages of the compile-time hash sum calculation
The problem we will try to solve is that every time the line get_bitmap_ resource is executed, the application will compute the hash
sum of the string "my_bitmap.png" at runtime. We want to perform this calculation at compile time so that when the application executes, the hash sum has already been calculated. In other words, just as we ...