#include v/s performance
(I defined this program in terms of a C++ program because I faced this thing while coding a C++ program, but the actual question is language-agnostic).
I had to copy chars from one char* buffer to another buffer. So, instead of doing a #include <cstring>
for strcpy
, I wrote a small snippet of code myself to do the same.
Here are the thoughts that I could think of then:
- Standard library functions are generally the fastest implementations that one can find of a certain code.
- But it would be unwise to include a big header file if you're going to use only a very minor part of it (that's what I think happens).
I want to know how right I was in doing so, and what can be defined as a bound of coding own snippets af开发者_开发知识库ter which one should revert to using headers.
The first rule of thumb is "don't reinvent the wheel". And remember that your wheel will probably be worse :-) (there are very good programmers that write the wheel provided by your compiler).
But yes, if I had to include the whole boost
library for a single function, I would try to directly copy it from the library :-)
I'll add that the question is marked as "language-agnostic", so we can't simply speak about the difference between C/C++ headers and C/C++ libraries. If we speak of a generic language, the inclusion of an external library COULD have side-effects, even BIG side-effects. For example it could slow down very much the startup of your program even if it isn't used (because it has static initializers that need to be called at startup, or it references flocks of other dll/dynamic libraries that need to be loaded). And it wouldn't be the first time there is an error in the startup of a program caused by the static startup of one of its dependancies :-)
So in the end "it depends". I would say that if only have to copy up to one file (let's say 250-500 lines) from a BSD source there isn't any big problem, for anything bigger linking to the library is probably necessary.
#include
-ing a header file should have no effect on runtime performance. It may, of course, slow down your compiler.
A decent linker should only pull in the pieces that it actually needs.
When you are talking about performance what do you want to optimize ? Compile time, size of binary/object, speed of execution ?
Using a standard library has the big advantage to improve code Maintainability and Readability. If someone else has to review or modify your code, it is much better to use the "standard" way.
It is much easier to spot a bug when calling memcpy() or strncpy() than when calling MyMemCpy() or MyStringCpy()
精彩评论