小编Eni*_*gma的帖子

使用 strlen 与停止为零的字符串操作的性能

当我用 C++ 为字符串编写一个类时,我发现了一个关于执行速度的奇怪行为。我将以upper方法的以下两个实现为例:

class String {

    char* str;

    ...

    forceinline void upperStrlen();
    forceinline void upperPtr();
};

void String::upperStrlen()
{
    INDEX length = strlen(str);

    for (INDEX i = 0; i < length; i++) {
        str[i] = toupper(str[i]);
    }
}

void String::upperPtr()
{
    char* ptr_char = str;

    for (; *ptr_char != '\0'; ptr_char++) {
        *ptr_char = toupper(*ptr_char);
    }
}
Run Code Online (Sandbox Code Playgroud)

INDEX 是 uint_fast32_t 的简单类型定义。

现在我可以在 main.cpp 中测试这些方法的速度:

#define TEST_RECURSIVE(_function)                    \
{                                                    \
    bool ok = true;                                  \
    clock_t before = clock();                        \
    for …
Run Code Online (Sandbox Code Playgroud)

c++ string performance gcc x86-64

6
推荐指数
1
解决办法
190
查看次数

标签 统计

c++ ×1

gcc ×1

performance ×1

string ×1

x86-64 ×1