我进行了以下测试。
charspeed.c

#include <stdio.h>
#include <time.h>

#define CHAR_COUNT 26
#define CHAR_LIST "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
static const char *CHAR_ARRAY = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

#define RUN_COUNT 1000000000

#define GET_CLOCK (float)clock() / CLOCKS_PER_SEC

int main()
{
    long long int sum = 0;
    float start, end;

    start = GET_CLOCK;
    for (size_t i = 0; i < RUN_COUNT; i++)
    {
        char test = CHAR_LIST[i % CHAR_COUNT];
        sum += test; // Force the loop to run!
    }
    end = GET_CLOCK;
    printf("#define Time: %f\n", end - start);

    start = GET_CLOCK;
    for (size_t i = 0; i < RUN_COUNT; i++)
    {
        char test = CHAR_ARRAY[i % CHAR_COUNT];
        sum += test; // Must be the same as fist loop!
    }
    end = GET_CLOCK;
    printf("static const *CHAR_ARRAY Time: %f\n", end - start);
    printf("sum = %lld\n", sum); // Must access "sum" after loops!
    return 0;
}

其输出
#define Time: 1.741000static const *CHAR_ARRAY Time: 1.868000
为什么使用#define指令的字符串文字要比预初始化的静态char数组更快?字符串文字到底存储在哪里,为什么在块作用域内访问它们更快呢?

使用的编译器选项为gcc -o charspeed charspeed.c

最佳答案

注意:已编辑为与OP的更改“同步”:

也许问题是您没有给出足够好的测试。一个好的编译器将在的时间内运行两个循环,因为它们内部没有任何后果。我尝试使用MSVC,并且您的代码两次都给出了0

但是,将循环数增加十倍并放入无法优化的部分,两者的时间几乎相等:

#include <stdio.h>
#include <time.h>

#define CHAR_COUNT 26
#define CHAR_LIST "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
static const char* CHAR_ARRAY = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

#define RUN_COUNT 1000000000 // Increased by factor of 10!
#define GET_CLOCK (double)clock() / CLOCKS_PER_SEC

int main()
{
    long long int sum = 0;
    double start, end;

    start = GET_CLOCK;
    for (size_t i = 0; i < RUN_COUNT; i++) {
        char test = CHAR_LIST[i % CHAR_COUNT];
        sum += test; // Force the loop to run!
    }
    end = GET_CLOCK;
    printf("#define Time: %lf\n", end - start);

    start = GET_CLOCK;
    for (size_t i = 0; i < RUN_COUNT; i++) {
        char test = CHAR_ARRAY[i % CHAR_COUNT];
        sum += test; // Must be the same as fist loop!
    }
    end = GET_CLOCK;
    printf("static const *CHAR_ARRAY Time: %lf\n", end - start);
    printf("sum = %lld\n", sum); // Must access "sum" after loops!
    return 0;
}

尝试在编译器/计算机上执行类似的操作,以查看它是否有所不同。

10-08 04:25