Page 1 of 1
STL or C style?
Posted: Wed Mar 15, 2006 3:14 pm
Question to more experienced C++ programmers: Just interesting which one makes code faster? using STL or self writing everything?
Posted: Wed Mar 15, 2006 5:10 pm
"Faster to write" or "shorter runtime"?
Posted: Wed Mar 15, 2006 5:40 pm
Posted: Wed Mar 15, 2006 6:05 pm
When you use STL, there has to be some overhead due to the fact that all the objects and algorithms you use are somehow "encapsulated" to allow their easier usage. However, this overhead isn't usually that big. I remember reading somewhere that the reasoning when doing the first STL implementation was "If the library were too slow, nobody would use it, so it makes no sense to waste time implementing a slow library".
For most practical reasons, the benefits you get from STL (shorter, more robust, less error-prone code) outweigh the not-that-big slowdown. In practice, I would only consider avoiding STL for programs where time is the most important issue (3D games come to mind).
One final note: as of today, the STL implementation in g++ relies heavily on compiler optimizations. There is a major difference in speed between STL code compiled with and without "-O2". I have even seen a situation when the times were as follows:
Code: Select all
STL solution with -O2: 10 seconds
my own solution: 12 seconds
STL solution without -O2: 45 seconds
but usually good low-level C code will be somewhat faster than the STL implementation.
Posted: Wed Mar 15, 2006 7:56 pm
Is there any exact experience with some exact classes, in which cases which one is better to use, or good old C style is always better?
Posted: Thu Mar 16, 2006 10:51 am
Another thing about the STL is that if used properly it can be faster than C code. Consider the qsort() function. It takes a function pointer as a parameter and uses that to compare two items. std::sort() does the comparision through a function object. A smart compiler could maybe inline the function object whereas it wouldn't inline the function pointer dereference.