|
|
Let's look at a solution to the same problem that uses the String component, one of the components in C++ Standard Components:
#include <String.h> String machine, service, dialstring; ... dialstring = machine + "." + service;Notice that the bookkeeping details that clutter the original example are gone. The bookkeeping is now taken care of behind the scenes, within the String component. Simplicity has not purchased at the price of performance, though. The above code is practically as efficient, both in time and space, as the code it replaces.
A word about such comparisons is called for. Comparing a C++ program written using general-purpose components with an ``equivalent'' hand-coded C program is like comparing a C program to an ``equivalent'' hand-coded assembly program: the C program may be a little bigger and a little slower than the assembly program, but it was probably easier and took less time to write, is more bug-free, and is easier to maintain and extend. That is not to say that one should ignore efficiency when writing in C++, any more than one should do so when writing in C! For us, efficiency, both in time and space, was our highest design goal. As a result, you should find that most uses of a component will be fast enough. If execution profiling reveals that a performance-critical program is spending too much time in component X, however, then you may need to replace the time-critical section with hand-crafted code. For String (and several other components) even this can be avoided by using special operations that we provide for users who need greater efficiency and are willing to understand some implementation details to achieve it. For example, if you know that the length of dialstring will almost always be less than 24 characters, then the following code guarantees that the concatenation will be extremely efficient:
#include <String.h> String machine, service, dialstring(24); ... dialstring.uniq(); ... dialstring = machine + "." + service;
If you want to know more about the String component, read ``No More String Errors - String(3C++)'' later in this guide. The title of the tutorial neatly epitomizes the pragmatic concerns behind the String component.