Back in 97, this article and another article by Todd published at DDJ, inspired me to write my own article at WDJ. In this article I applied the same technique to improve the performance of string concatenation operations. Consider the following code snippet (which uses CString, the MFC string class, but would hold for std::string as well):
CString a = "hello ";
CString b = "there ";
CString c = "world";
CString d = a + b + c;
This code actually translates to:
CString d = CString(a + b) + c;
This means a temporary object is created a destroyed and the contents of a and d are copied twice. Using template metaprogramming the expression a + b + c actually yields an object that represents the expression - a parse tree. A new constructor accepts this object type and traverses it twice: once to calculate to total length and a second time to perform the actual copy.
The result of this modification was a significant performance boost, without the class user needing to modify his code.
|