假设我们得到了以下代码,我们决定对其进行一些优化:
/// BM_NormalString
bool value = false;
std::string str;
str = "orthogonal";
if (str == "orthogonal") {
value = true;
}到目前为止,我们已经提出了两个非常简单和直接的策略:
/// BM_charString
bool value = false;
char *str = new char[11];
std::strcpy(str, "orthogonal");
if (std::strcmp(str, "orthogonal") == 0) {
value = true;
}
delete[] str;/// 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);如果我们尝试和基准测试我们的三种方法,我们,相当令人惊讶,将不会看到很大的区别。虽然板凳标记在当地给了我更令人惊讶的令人不安的结果:
| 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 |那么,你会说,对于如此小的字符串,几乎没有必要使用“裸金属”样式(使用C风格的字符串函数)吗?
发布于 2021-10-01 07:12:55
对于小字符串,使用动态存储是没有意义的。分配本身比比较慢。标准库实现者知道这一点,并对std::basic_string进行了优化,使其不使用带有小字符串的动态存储。
使用C-字符串不是“优化”。
https://stackoverflow.com/questions/69401716
复制相似问题