评估常量表达式的编译器

时间:2016-02-25 16:48:56

标签: c++ optimization

我希望我的编译器(VS 2013)避免任何冗余算术计算,最好是在编译时计算以下一次。

基本上我看到三种情况如下:

例如:

void Mesh::Draw1()
{
    const static uint32_t gStaticOffset = 0;
    const static uint32_t gVertexSize = sizeof(float) * 3;
    const static uint32_t gBoneIndexSize = sizeof(uint32_t) * MAX_BONES;
    const static uint32_t gBoneWeightSize = sizeof(float) * MAX_BONES;

    ...
}

VS

void Mesh::Draw2()
{
    const uint32_t staticOffset = 0;
    const uint32_t vertexSize = sizeof(float) * 3;
    const uint32_t boneIndexSize = sizeof(uint32_t) * MAX_BONES;
    const uint32_t boneWeightSize = sizeof(float) * MAX_BONES;

    ...
}

VS

const static uint32_t gStaticOffset = 0;
const static uint32_t gVertexSize = sizeof(float) * 3;
const static uint32_t gBoneIndexSize = sizeof(uint32_t) * MAX_BONES;
const static uint32_t gBoneWeightSize = sizeof(float) * MAX_BONES;

void Mesh::Draw3()
{
    ...  
}

我的想法,如果错误请纠正我:

  • Draw1()可能会重新计算每个函数调用的本地表达式 取决于编译器
  • Draw2()Draw3()保证表达式只计算一次, 如果不是在编译时,那么在运行时
  • 三种变体的任何表达式是否都是 在编译时评估完全取决于编译器

编译器是否会为每个代码生成不同的代码,如果是,哪一个避免了最冗余的计算?

1 个答案:

答案 0 :(得分:4)

除非你尝试,否则没有办法某些你的编译器会做什么。编译所有三个代码示例,然后查看生成的目标代码。

实际上,他们应该都是相同的。在编译器优化方面,常量折叠几乎是最低级的结果。如果您的编译器在编译时没有计算这些常量,那么不是优化编译器。除非你有非常充分的理由继续使用它,否则你应该把它交给垃圾堆找一个不同的。