SFML community forums
General => General discussions => Topic started by: FRex on May 12, 2013, 04:34:20 am
-
My question is, why some functions do not have overload for const char * but only const std::string& while const char * would make perfect sense.
Examples are basically all over the SFML with sf::String's constructor being proud example that you can actually pass c-string somewhere without the std::string terrorizing you with memory allocations.
Now: loadFromFile is not such a big deal, few dozen characters at most, unless you're loading things from insane filepaths, but loadFromMemory on sf::Shader is just evil. Shader source is expected to be quite long(at least around few dozens, going up to few hundred at most, but still much more than a path would have).
Also: other loadFromMemory take void * so why does loadFromMemory for Shader break out so much and instead of taking const char * take const std::string& which will probably copy quite a lot characters for no reason, and then call c_str() on that anyway while it could work perfectly good on my const char * that isn't in std::string?
Honestly if there was choice between the two, victory should go to const char *(but I'm not saying to remove std::strings from apis completely, just don't force it, especially with sf::Shader), you can go from std::string or any other reasonable string to const char * easily with c_str() or equivalent but to go from const char * or other string class class to std::string requires a copy.
-
"[...] premature optimization is the root of all evil." - Donald Knuth
While I can't speak for Laurent, I would argue that:
- This is C++, not C. It's idiomatic to use C++ strings in C++, not C strings in C++.
- There are times when the string length is needed. Passing an extra parameter (for C strings) is clumsy, and without passing an extra parameter strlen() must be called (which is O(n), compared to std::string::size(), which is O(1), and requires no additional parameter passing).
- This is a premature optimization. Chances are, text-based operations aren't the bottle neck of your program (either for CPU time or for memory). Optimizing something that accounts only for a fraction of your costs means you only get a fraction of a fraction of efficiency increase.
- Compilers are bloody good these days at optimizing. They're not perfect, sure, but even if std::string did introduce overhead, the optimizer would ensure that the overhead is minimal. Again, now you're optimizing a fraction of a fraction, which seems hardly worth anyone's time.
-
Don't fix what's not broken ;)