使用 c 风格的函数优化小 std::strings 通常毫无意义吗?
Is optimizing small std::strings wiht c-style functions often pointless?
假设我们有以下代码,我们决定对其进行一些优化:
/// 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 我们的三种方法,令人惊讶的是,我们不会看到太大的不同。
尽管在本地对其进行基准测试给了我更令人惊讶的令人不安的结果:
| 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 |
那么您会说,对于如此小的字符串,采用 'bare metal' 风格(通过使用 C 风格的字符串函数)几乎没有意义吗?
对于小字符串,使用动态存储没有意义。分配本身比比较慢。标准库实现者知道这一点并优化了 std::basic_string
以不对小字符串使用动态存储。
使用 C 字符串不是“优化”。
假设我们有以下代码,我们决定对其进行一些优化:
/// 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 我们的三种方法,令人惊讶的是,我们不会看到太大的不同。 尽管在本地对其进行基准测试给了我更令人惊讶的令人不安的结果:
| 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 |
那么您会说,对于如此小的字符串,采用 'bare metal' 风格(通过使用 C 风格的字符串函数)几乎没有意义吗?
对于小字符串,使用动态存储没有意义。分配本身比比较慢。标准库实现者知道这一点并优化了 std::basic_string
以不对小字符串使用动态存储。
使用 C 字符串不是“优化”。