Efficiency of C string vs C++ 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<s.size(). 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)