Ern*_*son 1 c++ string malloc char
假设我们有以下代码,并且我们决定对其进行一些优化:
/// BM_NormalString
bool value = false;
std::string str;
str = "orthogonal";
if (str == "orthogonal") {
value = true;
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我们已经提出了两个非常简单明了的策略:
/// BM_charString
bool value = false;
char *str = new char[11];
std::strcpy(str, "orthogonal");
if (std::strcmp(str, "orthogonal") == 0) {
value = true;
}
delete[] str;
Run Code Online (Sandbox Code Playgroud)
/// BM_charStringMalloc
bool value = false;
char *str = (char *) std::malloc(11);
std::strcpy(str, "orthogonal");
if (std::strcmp(str, "orthogonal") == 0) {
value = true;
}
free(str);
Run Code Online (Sandbox Code Playgroud)
如果我们尝试对三种方法进行基准测试,令人惊讶的是,我们不会看到太大的差异。尽管在本地进行基准测试给了我更令人惊讶的令人不安的结果:
| Benchmark | Time | CPU | Iterations |
|----------------------|------------------|-----------|---------------|
| BM_charString | 52.1 ns | 51.6 ns | 11200000 |
| BM_charStringMalloc | 47.4 ns | 47.5 ns | 15448276 |
| **BM_NormalString** | 17.1 ns | 16.9 ns | 40727273 |
Run Code Online (Sandbox Code Playgroud)
那么您是否会说,对于如此小的字符串,采用“裸机”风格(通过使用 C 风格的字符串函数)几乎没有意义?
对于小字符串,使用动态存储是没有意义的。分配本身比比较慢。标准库实现者知道这一点,并进行了优化std::basic_string,不使用小字符串的动态存储。
使用 C 字符串并不是一种“优化”。
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |