Avoiding Constructing Objects Using Proxy Objects
Explore how to optimize C++ code by avoiding the construction of temporary objects using proxy objects. Understand the implementation of a proxy class for string concatenation, enabling efficient comparisons without extra allocations. Learn about rvalue reference usage to prevent runtime errors and evaluate performance gains through benchmarking.
Eager evaluation can have the undesirable effect that objects are unnecessarily constructed. Often this is not a problem, but if the objects are expensive to construct (because of heap allocations, for example), there might be legitimate reasons to optimize away the unnecessary construction of short-lived objects that serve no purpose.
Comparing concatenated strings using a proxy
We will now walk through a minimal example of using proxy objects to give you an idea of what they are and can be used for. It’s not meant to provide you with a general production-ready solution to optimizing string comparisons.
With that said, take a look at this code snippet that concatenates two strings and compares the result:
Here is a visual representation of the preceding code snippet:
The problem is that (a + b) constructs a new temporary string to compare it with c. Instead of constructing a new string, we can compare the concatenation right away, ...