Why is C++ strings library more efficient? After all, underneath it all, aren't strings still represented as character arrays?
Because the code which uses char*
or char[]
is more likely to be inefficent if not written carefully. For example, have you seen loop like this:
char *get_data();
char const *s = get_data();
for(size_t i = 0 ; i < strlen(s) ; ++i) //Is it efficent loop? No.
{
//do something
}
Is that efficient? No. The time-complexity of strlen()
is O(N)
, and furthermore, it is computed in each iteration, in the above code.
Now you may say "I can make it efficient if I call strlen()
just once.". Of course, you can. But you have to do all that sort of optimization yourself and conciously. If you missed something, you missed CPU cycles. But with std::string
, many such optimization is done by the class itself. So you can write this:
std::string get_data();
std::string const & s = get_data(); //avoid copy if you don't need it
for(size_t i = 0 ; i < s.size() ; ++i) //Is it efficent loop? Yes.
{
//do something
}
Is that efficient? Yes. The time-complexity of size()
is O(1)
. No need to optimize it manually which often makes code look ugly and hard to read. The resulting code with std::string
is almost always neat and clean in comparison to char*
.
Also note that std::string
not only makes your code efficent in terms of CPU cycles, but it also increases programmer efficency!