C++ STL: still paying for what I don't use.
One of the great tenets of C++ has always been: "you don't
pay for what you don't use". Bjorn seems to use this very
line everytime he bashes Java or LISP-like languages. The later
is especially noteworthy since he is usually pretty honest
in acknowledging that functional languages do posses a number
of important qualities such as having an expressive power
of writing
qsort as a trivial two liner
qsort [] = []
qsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)
at the expense of wasting quite a lot of precious resources such
as RAM and CPU cycles.
Now, from time to time I see folks
showing examples of C++ code bordering on the same expressive
power. Take this little word counter ($ wc -w) for example:
int main() {
std::cout << std::distance(std::istream_iterator(std::cin),
std::istream_iterator());
return 0;
}
It looks impressive if nothing else, and since it is, after all, C++ everybody expects it to perform quite well. But does it?
To answer this question without dragging the reader into the dark realms
of assembly language or black art of performance measurements I would
really love to have a
good old Cfront
around. Or any other tool for that matter that would be able to retrace what
exactly all the templates and overloaded functions got expanded into. Alas, I
don't know of any such tool (if you do -- please leave a comment!). So bear
with me while I'll be using my stop watch ;-)
For the speed trial lets compare it to the similar code written in C (and
to make it fair I am going to even use scanf instead of a handcrafted code):
int main()
{
int count;
char buf[65535];
for (count = 0; scanf("%s", buf) != EOF; count++)
;
return printf("count %d\n", count);
}
Not that I am surprised, but C++ version ended up being 1.5 slower on my machine. And
if you compile the above example into .s file and look at what main() turned out
to be you can see a reason why. There is about 6 function calls there. Pretty much
nothing got inlined or computed in-place.
Bad implementation of a fine idea? Perhaps (I tried two: G++ and Sun Studio). But it
makes one wonder why in 28 years the world hasn't yet seen a good implementation. It's
not that the industry hasn't tried, you know.
Am I hearing the ghostly murmur of
Algol 68 or is it just my imagination?
Posted by rvs
@ 09:53 PM PDT
[
Comments [11]
]