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
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
'\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.