Efficiency of C-String vs C++Strings

前端 未结 8 669
忘掉有多难
忘掉有多难 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:30

    C-strings are usually faster, because they do not call malloc/new. But there are cases where std::string is faster. Function strlen() is O(N), but std::string::size() is O(1).

    Also when you search for substring, in C strings you need to check for '\0' on every cycle, in std::string - you don't. In a naive substring search algorithm it doesn't matter much, because instead of checking for '\0' you need to check for i. But modern high-performance substring search algorithms traverse strings in multibyte steps. And the need for a '\0' check in every byte slows them down. This is the reason why GLIBC memmem is x2 times faster than strstr. I did a lot of benchmarking of substring algorithms.

    This is true not only for substring search algorithm. Many other string processing algorithms are slower for zero-terminated strings.

提交回复
热议问题