Often you can see answers like “Avoid using C libraries in your C++ code“ or “This can be rewritten using STD/Boost in pure C++“.
I understand C++ produces more maintainable code and has many advantages, but is it actually bad using C libraries when performance is a priority? I mean writing in what is sometimes called C-with-classes.
I‘ve been developing a text file parser with both C and C++ versions and the C one was considerably faster.
What i would like to know is if using C libraries in C++ has hidden drawbacks apart from the obvious ones like making the code less maintainable.
7
is it actually bad using C libraries when performance is a priority?
It is if you don’t actually need the performance boost that the C library would provide, or the C library only produces a minimal performance increase, because you’re trading off too many of the benefits you get by using STD/Boost.
If:
- You profile your code using STD/Boost, and
- You profile your code using C libraries, and
- There is a significant performance improvement with the C libraries, and
- You actually need the performance improvement; i.e. using the C libraries fixes an actual performance problem
Then I would say that the C library is a better choice. But about 99 percent of the time, it won’t be the best choice, because the performance increase (if there is one) will be so small that it won’t be worth it.
Further Reading
Using/Mixing C in C++ code? on StackOverflow
2
C++ programmers seem to have a fear of not using enough of the language’s features all the time. ‘C with classes’ can be a perfectly acceptable solution if it solves your problem, and writing libraries in C gives you the advantage of being able to use them with other languages too.
You will have to ensure any resources allocated by you library have explicit ownership or you’ll get leaks.
Having said this I’m surprised your C code outperformed your C++ code, this indicates an issue with your C++ code (you’re probably using std::string all over the place)
1