Efficiency of C-String vs C++Strings

前端 未结 8 666
忘掉有多难
忘掉有多难 2020-12-28 14:20

C++ Primer says

For most applications, in addition to being safer, it is also more efficient to use library strings rather then C-style strings

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-28 14:51

    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!

提交回复
热议问题