C-String和C ++字符串的效率 [英] Efficiency of C-String vs C++Strings

查看:105
本文介绍了C-String和C ++字符串的效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ Primer说


对于大多数应用程序,除了更安全之外,字符串而不是C风格的字符串


安全被理解。为什么C ++字符串库更高效?毕竟,下面的所有,不是字符串仍然表示为字符数组?



为了澄清,作者谈论程序员的效率(理解)或处理效率? C>字符串通常更快,因为它们不调用malloc / new。但是有些情况下 std :: string 更快。函数 strlen()是O(N),但 std :: string :: size() )。



当你搜索substring时,在C字符串中你需要检查'\0'在每个周期,在 std :: string - 你不会。在一个朴素的子字符串搜索算法没有什么关系,因为不是检查'\0'你需要检查 i 。但是现代高性能子串搜索算法以多字节步长遍历字符串。并且每个字节需要一个'\0'检查会减慢它们。这就是为什么GLIBC memmem strstr 快x2倍的原因。我对子串算法进行了很多基准测试



这不仅适用于子字符串搜索算法。许多其他字符串处理算法对于零终止字符串较慢。


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

Safety is understood. Why is C++ strings library more efficient? After all, underneath it all, aren't strings still represented as character arrays?

To clarify, does author talk about programmer efficiency (understood) or processing efficiency?

解决方案

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 does not 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.

这篇关于C-String和C ++字符串的效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆